The "if" Statement

Very often, people will make an observation and then change their subsequent actions based on that observation. For example, someone going out or a walk might go through the following thought process:

If it looks like it might rain
	I will take an umbrella
otherwise
	I will leave my umbrella at home.

Such decision making is at the heart of computer programming. Very often, a program will either receive some data or perform a calculation and then change the actions it performs based on that occurence. For example, a program that calculated student grades might want to output a message "Congratulations on your good work!" if a student had done very well, but display a different message if the student's grades were low.

C allows decisions to be made using the if statement. The general form of the if statement is as follows:

    if ( condition )
    {
        /*if the condition is true,
          do whatever commands are contained 
          within the braces*/
    }
The condition must evaluate to either true or false. The following operators can be used in a condition statement:

Operator

Example

Description

==

a == b

This is the equivalence operator. It is true if a and b have the same value and false otherwise.

<

a < b

The less than operator is true if a is less than b and false otherwise.

>

a > b

This is the greater than operator. It is true if a is greater than b and false otherwise.

<=

a <= b

The less than or equal to operator is true as long as b is not greater thana.

>=

a >= b

The greater than or equal to operator is true as long as b is not less thana.

!

!a

The "not" or negation operator changes the truth value of what follows it. For the example, the condition !a is true if a is false.

The code snippet below shows an example of how an if statement could be used:

#include <stdio.h>

int main(int argc, char* argv[])
{
    /*create some test values for our if condition*/	
    int a, b;
    a = 10;
    b = -1;

    /*make a decision based on the values of a and b*/
    if(a > b)
    {
	  /*if a is greater than b, than execute this command*/	
        printf("The bigger number is a!\n");
    }

    return 0;
}

In the next section, we will look at more complex examples of the if statement and the condition term

next


 home                      table of contents                      about