Chapter 4: Conditional and Iterative Statements
In this chapter of this book, we shall be discussing what condition and iterative statements are. Condition execution is a construction of program statements that are optionally executed, but it depends on the context of the program’s execution. But on the other hand, iteration repeats the execution of a sequence of code. They are very useful in solving a lot of programming problems. Iteration and conditional executions are basically the key components of a good algorithm construction.
Conditional Execution
Type of Bool
Just as an arithmetic expression evaluates to numerical values, the Boolean expression evaluates to true
or false
. Boolean expression may look as though it is very limited on the surface, but they are essential for building interesting and useful programs. C++ supports the use of non-numeric data types bool,
which means Boolean. The word Boolean comes from a British mathematician George Boole. George Boole comes from a branch of discrete mathematic, also known as Boolean algebra dedicated to studying the properties and manipulation of logical expressions. Computing the numeric types, the bool
type of data is very simple, and they can represent only two values, true
or false
. Consider the simple program below which demonstrate the use of Boolean variables
Code 4.1
#include <iostream>
int main () {
// Declare three Boolean variables
bool x = true, y = false
std::cout << “x = “ << x <<< “, y = “ << y << ‘\n’;
// assign a value to x
x = false
std::cout << “x = “ << x << “, y = “ << y << ‘\n’;
// Mix integers and Boolean
x = 0;
y = 1;
std::cout << “x “ << x << “, y = “ << y << ‘\n’;
// Assign Boolean values to an integer
int a = x, b = true;
std::cout << “x = “ << x << “, y = “ << y
<< “, a = “ << a << “, b = “ << b << ‘\n’;
// More mixing
x = 1725 // Warning issued
y = - 19 // Warning issued
std::cout << “x = “ << x << “, y = “ << y << ‘\n’;
}
So, as you can see from the running code 4.1 above, the Boolean values true and falls are represented as integers 0 and 1. T0 be more precise, zero represents the bool value of false while the non-zero value, either positive or negative, represents the bool value of true.
Boolean Expression
The simplest form of a Boolean expression is true
or false
, which are the Boolean literals. Boolean variables are also known as a Boolean expression. An expression that compares numeric expressions for inequalities and equalities is also known as a Boolean expression. The simplest form of Boolean expressions makes use of relational operators to compare two expressions. Consider the table below; it shows some common simple Boolean expression and their associated values.
Expression
|
Value
|
10 < 20
|
Always true
|
10 > - 20
|
Always false
|
x == 10
|
True only if x has the value of 10
|
x != y
|
True unless x and y have the same values
|
C++ allows you to use simple expressions for example the statement
x == 20;
This expression may look as though you’re attempting to assign the values 20 to the variable x, but in truth, you’re not. The = operator performs the assignment but on the other hand, the operator == checks for relational equality. But if you should make a mistake and use the == operator where you meant to use the = operator, then the Visual C++ compiler will issue a warning message as follows:
Warning C4553: ‘==’: operator has no effect; did you intend ‘=’?
This warning doesn’t violate the rule of language, but it rather alerts you of a possible trouble spotted in the code.
The Simple IF Statement
The Boolean expressions are important in enabling a program to adapt its behavior at run time. A lot of practical and useful programs we see today are only possible because of the availability of the Boolean expression. The IF statement is a conditional statement that allows a program to be executable when certain conditions are met. Consider Code 4.2 below for a better understanding of how to use the IF statement.
Code 4.2
#include <iostream>
int main () {
int divided, divisor;
// Get two integers from the programmer
std::cout << “Please provide two integers to divide:”;
std::cin >> divided >> divisor;
// If possible, divide them and report the result
if (divisor !=0)
std::cout << divided << “/” << divisor << “ = “
<< divided/divisor << ‘\n’;
}
The second std::cout
may not always be executable. It depends on the values the user provided in the first std::cout
. If the user provides two integers, let’s say 20 and 5, the program is executable. Still, if the user enters a zero as a second number, then the program will not print anything after the user enters the values.
Compound Statements
There are times when you may have to execute more than one statement, optionally based on a particular condition. Consider the source code in code 4.3 below on how you must use curly braces to group multiple statements into one compound statement
Code 4.3
#include <iostream>
int main () {
int divided, divisor, quotient;
// Request two integers from the programmer
std::cout << “Please enter the two integers to divivde:”;
std::cin >> dividend >> divisor;
// If possible, divide them and report the result
if (divisor ! = 0) {
quotient = dividend / divisor;
std::cout << dividend << “ divided by “ << divisor << “ is “
<< quotient << ‘\n’;
}
}
The printing and assignment statement are both a part of the if
statement. Considering the true value of the Boolean expression divisor ! = 0 during a particular program run, either both statement be executed or neither of them will be executed. Compound statement consists of zero or more statements that are grouped in curly braces. We can say the curly braces define a block of statement. The programmer can also style up the code by always using curly braces to delimit the body of the if
statement even if the body contains only a statement.
The IF/ELSE Statement
One undesirable aspect of C++ is that when a user enters a zero as a divisor, it always prints nothing. The Visual C++ compiler may issue a feedback that the indicated divisor can’t be used. But the if
statement comes with an optional else
clause. The else
clause is executed only when the Boolean expression is false. Consider Code 4.4 to understand further how the if/else statement can be used.
Code 4.4
#include <iostream>
int main () {
int dividend, divisor;
// Request two integers from the programmer
std::cout << “Please provide two integers to divide:”;
std::cin >> dividend >> divisor;
// If possible, divide them and repost the result
if (divisor != 0)
std::cout << dividend << “/” << divisor << “ = “
<< dividend/divisor << ‘\n’;
else
std::cout << “Division by zero is not allowed\n”;
}
In Code 4.4 above, the if
and else
statement were used, and the program run will execute one of either. So, unlike the warning issue you get for entering a zero divisor, the else clause will alternate the body so that the program is executable. But when making use of the if/else statement in a statement, the following rule must apply:
●
The reserved word
if
must begin the
if/else
statement
●
The condition is a Boolean expression, which helps us to determine whether or not the running program will execute statement 1 or statement 2. As with the simple if statement, the condition must appear within the parentheses.
●
The program will only execute statement 1 if it satisfies the conditions (true).
●
To make the
if/else
statement more readable, indent statement 1 more than the
if
line. This section of the
if
statement is most often referred to as the body of the
if
.
●
The reserved world else always begins the second part of the
if/else
statement.
●
The program will only execute statement 2 if the condition is false.
●
To make the
if/else
statement more readable, indent statement 2 more than the
else
line. This section of the
if/else
statement is sometimes called the body of the
else
.
Nested Conditionals
Within the body of the if
or the else
statement, there could be any C++ statements included other if/else
statements, and in such cases, we call it nested conditionals. We can even nest an if
statement to build arbitrarily complex control flow logic. Consider code 4.5 below to see how we determined if a number is between 0 and 10 inclusive.
Code 4.5
#include <iostream>
int main () {
int value;
std::cout << “Please provide a range of integer between 0 . . . 10: “;
std::cin >> value;
if (value >=0) // First check
if (value <= 10) // Second check
std::cout << “In range”;
std::cout << “Done\n”;
}
In code 4.5, the program checks the value >= 0 condition first. If the value is less than zero, the program would not be able to execute the second condition and so would not print In range
but goes straight ahead and print the statement that follows the outer if statement which prints Done
. Also, if the executing program finds a value to be greater than or equal to zero, it checks the second condition. If the second condition is met, it displays the In range
message, but it is not met; it doesn’t display anything. Nevertheless, the program will print Done
before it terminates.
Iteration
The While Statement
Consider the code 4.6 below; while counts five by printing a number on each output line.
Code 4.6
#include <iostream>
int main () {
std::cout << 1 << ‘\n’;
std::cout << 2 << ‘\n’;
std::cout << 3 << ‘\n’;
std::cout << 4 << ‘\n’;
std::cout << 5 << ‘\n’;
}
When you compile and run this code, it will display on the screen 1 through 5. But how would you count to 10,000? Would you have to copy, paste, and modify 10,000 printing statements? You could do that, but it would be impractical. Because counting is one of the most common activity computers do, there has to be a better way to count it. So, what we can really do is to print the value of a variable and call it count
, then increment the variable (count++) and then repeat the process until the variable is large enough (count == 5 or perhaps count == 10000). Consider code 4.7 and see how we used the while statement to count to five.
Code 4.7
#include <iostream>
int main () {
int count = 1; // Initialize counter
while (count <= 5) {
std::cout << count << ‘\n’; //Display counter, then
count++; //Increment counter
}
}
Code 4.7 makes use of a while statement to display a variable that counts up to five. Unlike the approach taken in code 4.6, it is trivial to modify to count up to 10,000, just change the literal value 5 to 10000.
Nested Loops
Just like in the if
statement, the while
bodies can contain arbitrary C++ statements, including other while
statements. A loop can also be nested within another loop. To best understand how the nested loop works, consider a program that prints out a multiplication table. While we were in elementary school, we were taught the products of integers up to 10 or even 12 in some cases. And the same can be applied in C++ to even a much larger number.
Abnormal Loop Termination
By default, the while
statement executes, except its conditions become false. The abnormal loop that executes the program checks this condition only at the top of the loop. So, even if the Boolean expression makes up, the condition becomes false before the program completes executing all the statements within the body of the loop. The remaining statement in the loop’s body has to complete. Otherwise, the loop can once again check its condition. So, the while
statement cannot by itself exit its loop in the middle of its body. The abnormal loop termination can be divided into three sections:
-
The Break Statement
The C++ program provides a break
statement that implements the middle-existing control logic. This statement causes the immediate exit from the body of the loop. Consider code 4.8 below as we illustrate the use of break
Code 4.8
#include <iostream>
int main () {
int input, sum = 0;
std::cout << “Enter number to sun, negative number ends list:”;
while (true) {
std::cin >> input;
if (input < 0)
break; // Exit loop immediately
sum += input;
}
std::cout << “Sum = “ << sum << ‘\n’;
}
The condition of the while
in code 4.8 is a tautology. In other words, the condition is true and can never be false. When the statement reaches the while loop, it doesn’t provide a way out, so the if statement step in and provides a way out. In this scenario, the break
statement is executed conditionally based on the value of the variable input. The break statement executes only when the programmer enters a negative number.
-
The goto Statement
As we already know, the break statement can exit the single loop in which it is located. So, a break statement can’t just jump completely out of the middle of a nested loop. But the goto statement, on the other hand, allows the statement which allows the program execution flow to jump to a specified location in the function. Consider code 4.9 and how we use a goto statement to jump out of the middle of a nested loop.
Code 4.9
#include <iostream>
int main () {
// Compute some products
int op1 = 2;
while (op1 < 100) {
int op2 = 2;
while (op2 < 100) {
if (op1 * op2 == 3731)
goto end;
std::cout << “Product is “ << (op1 * op2) << ‘\n’ ;
op2++;
}
op1++;
}
end:
std::cout << “The end” << ‘\n’;
}
When op1 * op2 is 3731, program flow it jumps to a specified label within the program. In this example, the label name might end, but the name is arbitrary. And like in variable names, the label names should be chosen to indicate their intended purpose. The label named end comes outside and after the nested while
loops.
-
The Continue Statement
When a program’s execution encounters a break
statement inside a loop, it skips the remaining body of the loop and then exits the loop. The continue
statement is just like the break
statement, except that the continue
statement doesn’t necessarily exit the loop. In the continue statement, it skips the rest of the body of the loop and immediately checks the loop’s condition. If the loop’s condition remains true, then there would be an execution of the loops at the top of the loop. Consider Code 4.10 below to understand the continue statement in action better.
Code 4.10
#include <iostream>
int main () {
int input, sum = 0;
bool done = false;
while (!done) = false;
std::cout << Enter a positive integer (999 quits): “;
std::cin >> input;
if (input < 0) {
std::cout << “Negative value “ << input << “ ignored\n”;
continue; // skip rest of the body for this iteration
}
if (input != 999) {
std::cout << “Tallying “ << input << ‘\n’;
sum +=input;
}
else
done = (input == 99); // 999 entry exits loop
}
std::cout << “sum = “ << sum << ‘\n’;
}
Infinite Loops
An infinite loop is a type of loop with no exiting point. Once the program starts, it enters an infinite loop that it cannot escape. Some infinite loops are designed, for example, a long-running server application like a web server that needs to check for incoming connections continuously. This server application can perform this checking within a loop running indefinitely. Many times beginning programmers often create infinite loops by accident, which represent logic errors in their programs. An intentional infinite loop should look obvious. For example:
While (true) {
/* Do something forever . . . */
}
In Boolean literal, true is always true, and so a loop’s condition can’t be false. One way to exit a loop like this is with a break
statement, exit
call, or return
statement embedded within the body. It’s quite easy to write an intentional infinite loop.