if else statement
Syntax of the if - else statement
if (condition)
statement1;
else
statement2;
If-else Statement |
- From the above flowchart it is clear that the given condition is evaluated first. If the condition is true, statement1 is executed.
- If the condition is false, statement2 is executed. It should be kept in mind that statement and statement2 can be single or compound statement.
if example | if else example |
if (x == 100) | if (x == 100) |
if-else-if example |
if(percentage>=60) |
For Example
#include <iostream>
using namespace std;
int main ()
{
// declare local variable
int marks = 30;
// check the boolean condition
if( marks > 40 )
{
// if condition is true
cout << "You are pass !!" << endl;
}
else
{
// if condition is false
cout << "You are fail !!" << endl;
}
return 0;
}
Output :
You are fail !!
/* Program to find no. is even or odd*/
/* Program to find no. is even or odd*/
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n%2 == 0) {
cout << n << " is even.";
}
else {
cout << n << " is odd.";
}
return 0;
}
Output
Enter an integer: 23
23 is odd.