The if-else-if Ladder

The if statement lets you do something if a condition is true. If it isn’t true, nothing happens. But suppose we want to do one thing if a condition is true, and do something else if it’s false.

That’s where the if...else statement comes in. It consists of an if statement, followed by a statement or block of statements, followed by the keyword else, followed by another statement or block of statements.

Syntax of if....else Statement:

if(condition)
{
   // Statements inside body of if
}
else if(condition)
{
   //Statements inside body of else if
}
else 
{ 
     //Statements inside body of else 
}

 

Flow Diagram

Flow Diagram of if else statement

Example

// ifelse.cpp 
// demonstrates IF...ELSE statememt 
#include using namespace std; 

int main()
  { 
    int x;

    cout > x;
    if( x > 100 )
      cout << “That number is greater than 100
”;
    else
      cout << “That number is not greater than 100
”;
    return 0; 
 } 

Output:

Enter a number: 300
That number is greater than 100 
Enter a number: 3 
That number is not greater than 100