The if-Statement

  1. Selective execution of a group of statements based on a certain condition can be done using the if-statement

  2. The syntax of the if-statement is:

    if (Boolean_Expression)
         Yes_statement

    The Boolean expression is first evaluated to see if it is true or false. If it is true then the Yes_statement is executed, otherwise it is not executed. In either case control is passed on to the statement that follows the if-block.

    The single Yes_statement can be replaced by a compound statement. A compound statement is simply a group of statements enclosed by { and }. Note that there is no semi-colon after the right braces.

  3. For example, the following code:

    if (number_of_sales > target)
        Salary += bonus;
    cout << "Salary = " << Salary << endl;

    adds the bonus money to the salary only if the number of sales exceed the target number, and in any case always prints out the salary.

  4. A slightly more complicated case:

    if (number_of_sales > target)
    {
        Salary += bonus;
        cout << "Congratulation for a job well-done!" << endl;
    }
    cout << "You salary this month is: " << Salary << endl;

    adds the bonus money to the salary and print out a congratulatory statement only if the number of sales exceed the target number. In any case the salary is always printed out.