Pages

Saturday, February 27, 2010

THE if-else if STATEMENT


Introduction

If you want to make many decisions, then you can use the if-else if statement.

Program

The general format for the if-else if statement is:

if (condition 1)
simple or compound statement // s1
else if (condition 2)
simple or compound statement // s2
else if ( condition 3)
simple or compound statement // s3
.....
else if ( conditon n )
simple or compound statement // sn

If condition 1 is true then s1 is executed. If condition 1 is false and condition 2 is true then s2 is executed.

The else clause is always associated with the nearest unresolved if statement.

if (a==5)         // A
if (a==7) // B
i = 10; // C
else // D
if (a == 7) // E
i = 15; // F
else // G
i = 20; // H

For the else statement at position D, the nearest if statement is specified at B. So, the else statement is associated with if at B and not at A.

For the else statement at G, the nearest if statement is specified at E. So, it is associated with the if statement at E and not at A.

if (a==5)          // A
if (a==7) // B
i = 10; // C
else // D
if (a == 7) // E
i = 15; // F1
j = 20; // F2
else // G
i = 20; // H

In this case, the else statement at G cannot be associated with the if statement at E because the if statement at E is already resolved. So, it is associated with the if statement at A.

Points to Remember

  1. You can use if-else if when you want to check several conditions but still execute one statement.

  2. When writing an if-else if statement, be careful to associate your else statement to the appropriate if statement.

  3. You must have parentheses around the condition.

  4. You must have a semicolon or right brace before the else statement.

No comments:

Post a Comment