Examples of if statements

The following example causes grade to receive the value A if the value of score is greater than or equal to 90.

if (score >= 90)
   grade = 'A';

The following example displays Number is positive if the value of number is greater than or equal to 0. If the value of number is less than 0, it displays Number is negative.

if (number >= 0)
   printf("Number is positive\n");
else
   printf("Number is negative\n");

The following example shows a nested if statement:

if (paygrade == 7)
   if (level >= 0 && level <= 8)
      salary *= 1.05;
   else
      salary *= 1.04;
else
   salary *= 1.06;
cout << "salary is " << salary << endl;

The following example shows a nested if statement that does not have an else clause. Because an else clause always associates with the closest if statement, braces might be needed to force a particular else clause to associate with the correct if statement. In this example, omitting the braces would cause the else clause to associate with the nested if statement.

if (kegs > 0) {
   if (furlongs > kegs)
      fxph = furlongs/kegs;
}
else
   fxph = 0;

The following example shows an if statement nested within an else clause. This example tests multiple conditions. The tests are made in order of their appearance. If one test evaluates to a nonzero value, a statement runs and the entire if statement ends.

if (value > 0)
   ++increase;
else if (value == 0)
   ++break_even;
else
   ++decrease;

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]