Revisiting control structures, statements, and looping
C++ has a variety of control structures and looping constructs that allow for non-sequential program flow. Each can be coupled with simple or compound statements. Simple statements end with a semicolon; more compound statements are enclosed in a block of code using a pair of brackets {}. In this section, we will be revisiting various types of control structures (if, else if, and else), and looping constructs (while, do while, and for) to recap simple methods for non-sequential program flow within our code.
Control structures – if, else if, and else
Conditional statements using if, else if, and else can be used with simple statements or a block of statements. Note that an if clause can be used without a following else if or else clause. Actually, else if is really a condensed version of an else clause with a nested if clause inside of it. Practically speaking, developers flatten the nested use into else if format for readability and to save excess indenting. Let’s see an example:
#include <iostream>
using namespace std; // we'll limit the namespace shortly
int main()
{
int x = 0;
cout << "Enter an integer: ";
cin >> x;
if (x == 0)
cout << "x is 0" << endl;
else if (x < 0)
cout << "x is negative" << endl;
else
{
cout << "x is positive";
cout << "and ten times x is: " << x * 10 << endl;
}
return 0;
}
Notice that in the preceding else clause, multiple statements are bundled into a block of code, whereas in the if and else if conditions, only a single statement follows each condition. As a side note, in C++, any non-zero value is considered to be true. So, for example, testing if (x) would imply that x is not equal to zero – it would not be necessary to write if (x !=0), except possibly for readability.
It is worth mentioning that in C++, it is wise to adopt a set of consistent coding conventions and practices (as do many teams and organizations). As a straightforward example, the placement of brackets may be specified in a coding standard (such as starting the { on the same line as the keyword else, or on the line below the keyword else with the number of spaces it should be indented). Another convention may be that even a single statement following an else keyword be included in a block using brackets. Following a consistent set of coding conventions will allow your code to be more easily read and maintained by others.
Looping constructs – while, do while, and for loops
C++ has several looping constructs. Let’s take a moment to review a brief example for each style, starting with the while and do while loop constructs:
#include <iostream>
using namespace std; // we'll limit the namespace shortly
int main()
{
int i = 0;
while (i < 10)
{
cout << i << endl;
i++;
}
i = 0;
do
{
cout << i << endl;
i++;
} while (i < 10);
return 0;
}
With the while loop, the condition to enter the loop must evaluate to true prior to each entry of the loop body. However, with the do while loop, the first entry to the loop body is guaranteed – the condition is then evaluated before another iteration through the loop body. In the preceding example, both the while and do while loops are executed 10 times, each printing values 0-9 for variable i.
Next, let’s review a typical for loop. The for loop has three parts within the (). First, there is a statement that is executed exactly once and is often used to initialize a loop control variable. Next, separated on both sides by semicolons in the center of the () is an expression. This expression is evaluated each time before entering the body of the loop. The body of the loop is only entered if this expression evaluates to true. Lastly, the third part within the () is a second statement. This statement is executed immediately after executing the body of the loop and is often used to modify a loop control variable. Following this second statement, the center expression is re-evaluated. Here is an example:
#include <iostream>
using namespace std; // we'll limit the namespace shortly
int main()
{
// though we'll prefer to declare i within the loop
// construct, let's understand scope in both scenarios
int i;
for (i = 0; i < 10; i++)
cout << i << endl;
for (int j = 0; j < 10; j++) // preferred declaration
cout << j << endl; // of loop control variable
return 0;
}
Here, we have two for loops. Prior to the first loop, variable i is declared. Variable i is then initialized with a value of 0 in statement 1 between the loop parentheses (). The loop condition is tested, and if true, the loop body is then entered and executed, followed by statement 2 being executed prior to the loop condition being retested. This loop is executed 10 times for i values 0 through 9. The second for loop is similar, with the only difference being variable j is both declared and initialized within statement 1 of the loop construct. Note that variable j only has scope for the for loop itself, whereas variable i has scope of the entire block in which it is declared, from its declaration point forward.
Let’s quickly see an example using nested loops. The looping constructs can be of any type, but in the following, we’ll review nested for loops:
#include <iostream>
using namespace std; // we'll limit the namespace shortly
int main()
{
for (int i = 0; i < 10; i++)
{
cout << i << endl;
for (int j = 0; j < 10; j++)
cout << j << endl;
cout << "\n";
}
return 0;
}
Here, the outer loop will execute ten times with i values of 0 through 9. For each value of i, the inner loop will execute ten times, with j values of 0 through 9. Remember, with for loops, the loop control variable is automatically incremented with the i++ or j++ within the loop construct. Had a while loop been used, the programmer would need to remember to increment the loop control variable in the last line of the body of each such loop.
Now that we have reviewed control structures, statements, and looping constructs in C++, we can move onward by briefly recalling C++’s operators.