Cloudbook: C

  1. Home
  2. Control
  3. If/Else
  4. § 3 exercise →
If/Else

The else clause is an optional part of the if statement. It else clause follows an if statement and runs its code block only if the controlling expression evaluates false. In the if/else construct, it is certain that one and only one of the two code blocks will be run — the block of the if statement if the controlling expression is true, the block of the else clause if the controlling expression is false.

In computers, things are either true or false.

These constructs can be nested. That means either the if block or the else block can themselves contain if and if/else statements.

Suppose three actions are to be taken on the value of a numbers stored in $i, too cold, too hot, and just right. This can be done by nesting a if/else inside one of the blocks of another if/else.

The nesting can first check for too hot. If it's too hot, say "Ouch!" Else, since it's not too hot, check whether it is too cold or not. If it is too cold, say "Brrrr!"; else say "Mmm ...".

The associated exercise gives an example of an if/else statement. Study the syntax. The general format is

        if ( logical-expression ) { if-block }
        else { else-block } 
The associated exercise asks you to puzzle out as an exercise the code that sorts out the three alternatives, by using nested if/else statements.