Selections in C++: if Statements

An if statement is a construct that enables a program to specify alternative path of execution.

The programs that you have written so far execute in sequence. However, often there are situations in which you must provide alternative paths. C++ provides several types of selec­tion statements: one-way if statements, two-way if-else statements, nested if statements, switch statements, and conditional expressions.

A one-way if statement executes an action if and only if the condition is true. The syntax for a one-way if statement is shown here:

if (boolean-expression)

{

statement(s);

}

The flowchart in Figure 3.1a illustrates how C++ executes the syntax of an if statement. A flowchart is a diagram that describes an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. Process operations are represented in these boxes, and arrows connecting them represent flow of control. A dia­mond box is used to denote a Boolean condition and a rectangle box is used to represent statements.

If the boolean-expression evaluates to true, the statements in the block are executed. As an example, see the following code:

if (radius >= 0)

{

area = radius * radius * PI;

cout << “The area for the circle of ” <<

” radius ” << radius << ” is ” << area;

}

The flowchart of the preceding statement is shown in Figure 3.1b. If the value of radius is greater than or equal to 0, then the area is computed and the result is displayed; otherwise, the two statements in the block will not be executed.

The boolean-expression is enclosed in parentheses. For example, the code in (a) below is wrong. The corrected version is shown in (b).

The braces can be omitted if they enclose a single statement. For example, the following statements are equivalent.

Listing 3.1 gives a program that prompts the user to enter an integer. If the number is a multiple of 5, display HiFive. If the number is even, display HiEven.

Listing 3.1 SimplelfDemo.cpp

1 #include <iostream>

2 using namespace std;

3

4 int main()

5 {

6    // Prompt the user to enter an integer

7    int number;

8    cout << “Enter an integer: “;

9    cin >> number;

10

11    if (number % 5 == 0)

12    cout << “HiFive” << endl;

13

14    if (number % 2 == 0)

15    cout << “HiEven” << endl;

16

17    return 0;

18 }

The program prompts the user to enter an integer (line 9) and displays HiFive if it is mul­tiple by 5 (lines 11-12) and HiEven if it is even (lines 14-15).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *