Chapter 10 Branching and Looping
In this chapter, we will look at how C++ implements if-statements and
looping. Broadly speaking, these are identical to Python’s
implementations, although there are some minor differences. We will
start off with if
statements, and then continue on to loops, covering
for
loops, while
loops and a new kind of loop: the do-while
loop.
10.1 If-statements
The standard if-statement in C++ is very similar to Python. To illustrate, we first show the general form of an if-else snippet in Python:
if <exp>:
# do something
else:
# do something else
The C++ equivalent of this is as follows
if (<exp>){
// do something
}
else{
// do something else
}
Not the main differences between the two. In Python, we use colons and indentation to indicate which statements should be executed if the condition is true or false. In C++ however, we use curly braces to indicate this (C++ does not care about indentation, but we use it to make the code more readable to humans). Additionally, the logical expression being evaluated by the if-statement must be inside round brackets. Other than those two aspects, everything remains the same.
Note that the same rules apply to C++: as in Python the else
condition
is optional, but if it is present it must be attached to an
if-statement.
Let us now look at the situation where we have multiple cases to be
checked. One difference here is that C++ does not possess the elif
.
Instead, we must write else if
in full. In the Python program below,
we read a mark from the user, and display the corresponding symbol:
= int(input())
grade if grade >= 75:
print("A")
elif grade >= 70:
print("B")
elif grade >= 60:
print("C")
elif grade >= 50:
print("D")
else:
print("F")
The equivalent C++ program is as follows (note the use of else if
):
#include <iostream>
using namespace std;
int main(){
int grade;
>> grade;
cin if (grade >= 75){
<< "A" << endl;
cout }
else if (grade >= 70){
<< "B" << endl;
cout }
else if (grade >= 60){
<< "C" << endl;
cout }
else if (grade >= 50){
<< "D" << endl;
cout }
else{
<< "F" << endl;
cout }
return 0;
}
Finally, as in Python, we can also nest if-statements inside one another. The following examples in Python and C++ illustrate this:
# Python program
= int(input())
num if num % 2 == 0:
if num % 3 == 0:
print("Div by 2 and 3")
else:
print("Div by 2; not by 3")
else:
if num % 3 == 0:
print ("Div by 3; not by 2")
else:
print ("Not div by 2 and 3")
//C++ program
#include <iostream>
using namespace std;
int main(){
int num;
>> num;
cin if (num % 2 == 0){
if (num % 3 == 0){
<< "Div by 2 and 3" << endl;
cout }
else{
<< "Div by 2; not by 3" << endl;
cout }
}
else{
if (num % 3 == 0){
<< "Div by 3; not by 2" << endl;
cout }
else{
<< "Not div by 2 and 3" << endl;
cout }
}
return 0;
}
Because C++ uses curly braces, there’s a chance you may have too many or too few by mistake. You can reduce these errors by using proper indentation, so that the closing brace lines up with the statement it belongs to (as in the above example). This makes it easy to see which brace belongs to which statement.
10.2 Loops
We have previously covered while-loops, for-loops and associated
statements such as break
and continue
in Python. As we shall see,
C++ supports these exact same features. As in the previous section, we
will be using curly braces instead of indentation and colons to indicate
the loop-body (that is, the code to be executed while the condition
remains true).
10.2.1 While-loops
To begin, we contrast the while-loop in Python and then C++. In Python, we have
while <exp>:
# statement 1
# statement 2
# etc
C++ looks almost identical but again note that we use curly braces and that the loop’s logical expression must be inside round brackets.
while (<exp>){
// statement 1
// statement 2
// etc
}
A full example of a while loop in action is given below, where we read in a series of 10 marks and determine the number of passes and failures: First, in Python:
= 0
passes = 0
failures = 0
n_students while n_students < 10:
= int(input())
mark if mark >= 50:
= passes + 1
passes else:
= failures + 1
failures = n_students + 1
n_students
print("Passes", passes)
print("Failures", failures)
Then, the equivalent program in C++
#include <iostream>
using namespace std;
int main(){
int passes = 0;
int failures = 0;
int nStudents = 0;
int mark;
while (nStudents < 10){
>> mark;
cin if (mark >= 50){
= passes + 1;
passes }
else{
= failures + 1;
failures }
= nStudents + 1;
nStudents }
<< "Passes " << passes << endl;
cout << "Fails " << failures << endl;
cout return 0;
}
10.2.2 For-loops
Recall that in Python, a simple for-loop takes the following form:
for i in range(start, stop, step):
# statement 1
# statement 2
# etc
In C++, this looks slightly different, but has the same semantic meaning. The equivalent C++ for-loop is as follows:
for (int i = start; i < stop; i = i + step){
// statement 1
// statement 2
// etc
}
The first thing to notice is that inside the round brackets there are
three statements, separated by a semi-colon. Note that we are
introducing a new variable i
, and so we must specify its type the
first time it is mentioned. These statements are known as the
initialisation expression, termination condition expression and
variable update expression. A more general form of the C++ for-loop is
as follows:
for (<exp_1>; <exp_2>; <exp_3>){
// loop body
}
<exp_1>
initialises the control variable<exp_2>
is the termination condition<exp_3>
changes the control variable and is executed after the loop body
In more detail, the initialisation expression allows you to declare and initialise a control variable before the loop begins (or assign a value to an existing variable). This expression is executed only once before the loop, and never again. The termination condition expression is a boolean test that determines whether the body of the loop should be executed. Finally, the variable update expression allows us to modify the control variable in some manner. After the first execution of the loop body, the variable is updated, and the condition is checked. If the condition is still true, the loop body repeats, after which the variable is updated, and so forth. Each of the above three expressions is optional and so can be omitted, but the semicolons are mandatory. Note that if the condition is empty, it is evaluated as true and the loop will repeat indefinitely (unless we stop it some other way).
We now show the for-loop in action, using the same pass/fail calculator program in the previous section. For reference, we first show the Python program:
= 0
passes = 0
failures for n_students in range(0, 10, 1):
= int(input())
mark if mark >= 50:
= passes + 1
passes else:
= failures + 1
failures
print("Passes", passes)
print("Failures", failures)
Then, in C++:
#include <iostream>
using namespace std;
int main(){
int passes = 0;
int fails = 0;
int mark;
for (int nStudents = 0; nStudents < 10; ++nStudents){
>> mark;
cin if (mark >= 50){
= passes + 1;
passes }
else{
= failures + 1;
failures }
}
<< "Passes " << passes << endl;
cout << "Fails " << fails << endl;
cout return 0;
}
Note that we have used the increment operator and written ++nStudents
.
Recall from a previous chapter that this is equivalent to
nStudents += 1
which itself is equivalent to
nStudents = nStudents + 1
. It is a very convenient way of adding one
to a variable, and is frequently used in for-loops. C++ provides two
increment operators: x++
and ++x
. They are subtly different, but for
our purposes are identical. Thus we can write nStudents++
or
++nStudents
.
Programming language side quest! The increment operator ++
appears in the language we’re currently using! This is because C++ was designed to be an upgrade of the language C. But what was C an improvement upon? Find out the language that C was based on, then download a compiler for it and try reproduce some of the code examples here in that language!
10.2.3 Do-While loop
The do-while loop is similar to the while-loop, and does not have an equivalent in Python. It is useful when we want to ensure that the loop runs at least once. A good use-case for this is displaying a menu to a user. In this case, we would always want the user to see the menu at least once, even if they then simply quit the program. The general form of this loop looks like this:
do{
// statement 1
// statement 2
// etc
}
while (<exp>); //NB: semicolon!
Note that unlike the while-loop, the condition appears after the loop body. Thus the loop body is always executed at least once. In practice, the do-while loop is rarely used, and the while-loop is much more common.
Question! Can you think of other use cases where a do-while loop would be useful?
10.2.4 Break and Continue
The break
and continue
statements are identical to their Python
versions. Of course, since we are using C++, the statements must end
with a semi-colon. An example of the continue statement is below:
for i in range(3, 20):
if i == 7:
continue
print(i)
for (int i = 3; i < 20; ++i){
if (i == 7){
continue;
}<< i << endl;
cout }
10.3 Summary Lecture