if-else if-else statement (Glossary Entry)

Conditional statements are what add the decision making and to some extent, business logic to software. At a fundamental level, a computer does only a few distinct tasks:

  • Fetch and store
  • Modify (arithmetic and bitwise operations)
  • Flow control (conditionally branch)

Like the while and do-while statements, the if-else if-else also performs conditional tests, but in contrast, they do not perform iteration (looping).

Single IF statement

The simplest for is the single if statement. This construct simply executes an additional block of code when a condition is found to be true (non zero in C).

if ( <conditional statement>)  {

//Consequent Process

}

This is depicted in the following flow-chart.

Note how the consequent branch re-joins the main program flow.

if-else

A Boolean condition is either TRUE or FALSE. You use the combination of if and else statements to perform different processes for each outcome. This construct simply executes one block of code for the TRUE condition, and another block of code for the FALSE.

if ( <conditional statement>)  {

//Consequent Process for TRUE

} else {

//Consequent Process for FALSE

}

This is depicted in the following flow-chart.

Once again, the code rejoins the main flow.

if-else if-else

This is used to test multiple conditions using a process of elimination. As with the previous two cases, the outcome always results with one block of code (consequent process) being exclusively executed.

if ( <conditional statement 1>)  {

//Consequent Process for Conditional Statement 1

} else if ( <conditional statement 2>)  {

//Consequent Process for Conditional Statement 2

} else if ( <conditional statement N>)  {

//Consequent Process for Conditional Statement N

} else {

//Consequent Process for all other conditions

//(optional)

}

 

This is depicted in the following flow-chart.

Note again that each consequent process is mutually exclusive and evaluated in a specific sequence. For example, if both conditional statements A and B happen to be TRUE, only consequent process A would execute as this is tested first.

Contrast this with multiple if-else statements

 

if ( <conditional statement 1>)  {

//Consequent Process for Conditional Statement 1

} else {

//Complimentary Consequent Process 

}

if ( <conditional statement 2>)  {

//Consequent Process for Conditional Statement 2

} else {

//Complimentary Consequent Process 

}

if ( <conditional statement N>)  {

//Consequent Process for Conditional Statement N

} else {

//Complimentary Consequent Process 

}

This is depicted in the following flow-chart.

Note the key difference here. ALL conditions are tested in order. For example, if conditional statements A and C are both true, then consequent processes A and B will both be executed (in sequence).