Holla Tech - Learn

Nested if Statements
 

An if statement can include another if statement to form a nested statement. Nesting an if allows a decision to be based on further requirements.
Consider the following statement: 

if (profit > 1000)
  if (clients > 15)
    bonus = 100;
  else
    bonus = 25

 

Appropriately indenting nested statements will help clarify the meaning to a reader. However, be sure to understand that an else clause is associated with the closest if unless curly braces { } are used to change the association.
For example:

if (profit > 1000) {
  if (clients > 15)
    bonus = 100;
}
else
  bonus = 25

 

NOTE!
You can try out the code output using a code editor that is responsive to C language.

The if-else if Statement
 

When a decision among three or more actions is needed, the if-else if statement can be used.
There can be multiple else if clauses and the last else clause is optional.
For example:

int score = 89;
 
if (score >= 90)
  printf(“%s”, “Top 10%\n”);
else if (score >= 80)
  printf(“%s”, “Top 20%\n”);
else if (score > 75)
  printf(“%s”, “You passed.\n”);
else
  printf(“%s”, “You did not pass.\n”);

 

Carefully consider the logic involved when developing an if-else if statement. Program flow branches to the statements associated with the first true expression and none of the remaining expressions will be tested.
Although indents won’t affect the compiled code, the logic of the if-else if will be easier to understand by a reader when the else clauses are aligned.

NOTE!
When possible, an if-else if statement is preferred over nested if statements for clarity.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT