if (condition)

{

    statement;

    statement;

    .

    .

   statement;

}

 

Note the indentation of the lines and semi-colon after each statement. Semi-colons are necessary after every C statement. The indentation is only a matter of style. It makes the code easy to read and understand from where a block starts, ends and what kind of block it is. It does not affect the logic of the program. But the braces can affect the logic. We can also write a comment line to state the purpose of code block.

Let's consider a simple example to explain the if statement. Suppose, we have ages of two students (say for the time being we have got these ages in variables). These variables are- age1 and age2. Now we say that if the age1 is greater than age2, then display the statement ‘Student 1 is older than student 2’.

The coding for this program will be as below

 

#include <iostream.h>

main()

{

            int age1, age2;

            age1 = 12;

            age2 = 10;

            if (age1 > age2)

                 cout << “Student 1 is older than student 2”;

}

 

 

 

Previous

 

 

TOC

 

 

Next