The "if" Statement (continued)

The basic if statement is useful in many cases, but it is somewhat limited. Often, it is desirable to write a program that will take one of several different actions based on what conditions are currently true. The slightly more complicated if...else structure accomodates this. It has the following form:

	if ( condition1 )
	{
		/*do command set one*/
	}
	else if ( condition2 )
	{
		/*do command set two*/
	}
	else if ( condition3)
	{
		/*do command set three*/
	}
	.
	.	/*could include more  else if  clauses here*/
	.
	else
	{
		/*if every other condition fails, do the commands here*/
	}

	/*program continues here*/

The if...else structure can have as many else if clauses as you like, but only one opening if and only one else at the end of the sturcture.

The code that will be executed in if structure is the code that the follows the first condition that is satisfied. Once the program executes the code between a pair of braces, execution transfers to the end of the if structure. For example, given the above structure, if condition1 was false and condition2 and condition3 were both true, the first if statement would fail, and the program would check the first else if. This would succeed and command set two would be executed. The program would then start executing commands at the end of the if structure where it says "/*program continues here*/". Command set three would never be executed, because condition2 was satisfied before it.

The else clause at the end of the struture will alays be satisfied. The code here will be executed if every condition above has failed. The else clause is optional and need not be included in the if structure.

A trivial example of an if..else statement is shown below:

#include <stdio.h>

int main(int argc, char* argv[])
{

    int a, b;

    //set any values you like
    a = 10;
    b = 20;

    if ( a > b )
    {
        printf("a is bigger than b!\n");
    }
    else if ( a == b )
    {
        printf("a is equal to b!\n");
    }
    else
    {
        printf("a is smaller than b :( \n");
    }

    return 0;
}

next


 home                      table of contents                      about