A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done to perform our program.
With the introduction of control sequences we are going to have to introduce a new concept: the block of instructions. A block of instructions is a group of instructions separated by semicolons (;) but grouped in a block delimited by curly bracket signs: { and }.
Most of the control structures that we will see in this section allow a generic statement as a parameter, this refers to either a single instruction or a block of instructions, as we want. If we want the statement to be a single instruction we do not need to enclose it between curly-brackets ({}). If we want the statement to be more than a single instruction we must enclose them between curly brackets ({}) forming a block of instructions.
Conditional structure: if and else
It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its form is:
1 2 3 | if (condition) statement |
where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues on the next instruction after the conditional structure.
For example, the following code fragment prints out x is 100 only if the value stored in variable x is indeed 100:
1 2 3 4 | if (x == 100) cout << "x is 100"; |
If we want more than a single instruction to be executed in case that condition is true we can specify a block of instructions using curly brackets { }:
1 2 3 4 5 6 7 | if (x == 100) { cout << "x is "; cout << x; } |
We can additionally specify what we want that happens if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:
1 2 3 | if (condition) statement1 else statement2 |
For example:
1 2 3 4 5 6 | if (x == 100) cout << "x is 100"; else cout << "x is not 100"; |
prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it prints out x is not 100.
The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the present value stored in x is positive, negative or none of the previous, that is to say, equal to zero.
1 2 3 4 5 6 7 8 | if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; |
Remember that in case we want more than a single instruction to be executed, we must group them in a block of instructions by using curly brackets { }.
Repetitive structures or loops
Loops have as objective to repeat a statement a certain number of times or while a condition is fulfilled.
while loop in C++
- Its format is:
- 123while (expression) statement
- and its function is simply to repeat statement while expression is true.For example, we are going to make a program to count down using a while loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // custom countdown using while #include <iostream.h> int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!"; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main () { // Local variable declaration: int a = 10; // while loop execution while( a < 20 ) { cout << "value of a: " << a << endl; a++; } return 0; } |
When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n be greater than 0 ), the block of instructions that follows will execute an indefinite number of times while the condition (n>0) remains true.
All the process in the program above can be interpreted according to the following script: beginning in main:
1. User assigns a value to n.
2. The while instruction checks if (n>0). At this point there are two possibilities:
- true: execute statement (step 3,)
- false: jump statement. The program follows in step 5..
3. Execute statement:
1 2 3 4 | cout << n << ", "; --n; |
(prints out n on screen and decreases n by 1).
4. End of block. Return Automatically to step 2.
5. Continue the program after the block: print out FIRE! and end of program.
We must consider that the loop has to end at some point, therefore, within the block of instructions (loop’s statement) we must provide some method that forces condition to become false at some moment, otherwise the loop will continue looping forever. In this case we have included --n; that causes the condition to become false after some loop repetitions: when n becomes 0, that is where our countdown ends.
Of course this is such a simple action for our computer that the whole countdown is performed instantly without practical delay between numbers.
do-while loop in C++
Format:
1 2 3 | do statement while (condition); |
Its functionality is exactly the same as the while loop except that condition in the do-while is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following program echoes any number you enter until you enter 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // number echoer #include <iostream.h> int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main () { // Local variable declaration: int a = 10; // do loop execution do { cout << "value of a: " << a << endl; a = a + 1; } while( a < 20 ); return 0; } |
The do-while loop is usually used when the condition that has to determine its end is determined within the loop statement, like in the previous case, where the user input within the block of intructions is what determines the end of the loop. If you never enter the 0 value in the previous example the loop will never end.
for loop in C++
Its format is:
1 2 3 | for (initialization; condition; increase) statement; |
and its main function is to repeat statement while condition remains true, like the while loop. But in addition, for provides places to specify an initialization instruction and an increase instruction. So this loop is specially designed to perform a repetitive action with a counter.
It works the following way:
- initialization is executed. Generally it is an initial value setting for a counter varible. This is executed only once.
- condition is checked, if it is true the loop continues, otherwise the loop finishes and statement is skipped.
- statement is executed. As usual, it can be either a single instruction or a block of instructions enclosed within curly brackets { }.
- finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
Here is an example of countdown using a for loop.
1 2 3 4 5 6 7 8 9 10 11 12 | // countdown using a for loop #include <iostream.h> int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!"; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> using namespace std; int main () { // for loop execution for( int a = 10; a < 20; a = a + 1 ) { cout << "value of a: " << a << endl; } return 0; } |
Bifurcation of control and jumps
break
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before it naturally finishes (an engine failure maybe):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // break loop example #include <iostream.h> int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; } |
continue
The continue instruction causes the program to skip the rest of the loop in the present iteration as if the end of the statement block would have been reached, causing it to jump to the following iteration. For example, we are going to skip the number 5 in our countdown:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // break loop example #include <iostream.h> int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!"; return 0; } |
goto
It allows making an absolute jump to another point in the program. You should use this feature carefully since its execution ignores any type of nesting limitation.
The destination point is identified by a label, which is then used as an argument for the goto instruction. A label is made of a valid identifier followed by a colon (:).
This instruction does not have a concrete utility in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // goto loop example #include <iostream.h> int main () { int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!"; return 0; } |
exit function.
exit is a function defined in cstdlib (stdlib.h) library.
The purpose of exit is to terminate the running program with an specific exit code. Its prototype is:
1 2 3 | void exit (int exit code); |
The exit code is used by some operating systems and may be used by calling programs. By convention, an exit code of 0 means that the program finished normally and any other value means an error happened.
Selective Structure: switch.
The syntax of the switch instruction is a bit peculiar. Its objective is to check several possible constant values for an expression, something similar to what we did at the beginning of this section with the linking of several if and else ifsentences. Its form is the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | switch (expression) { case constant1: block of instructions 1 break; case constant2: block of instructions 2 break; . . . default: default block of instructions } |
It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes block of instructions 1 until it finds the break keyword, then the program will jump to the end of the switchselective structure.
If expression was not equal to constant1 it will check if expression is equivalent to constant2. If it is, it will execute block of instructions 2 until it finds the break keyword.
Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case sentences as values you want to check), the program will execute the instructions included in the default:section, if this one exists, since it is optional.
Both of the following code fragments are equivalent:
1 2 3 4 5 6 7 8 9 10 11 12 | switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; } |
I have commented before that the syntax of the switch instruction is a bit peculiar. Notice the inclusion of the break instructions at the end of each block. This is necessary because if, for example, we did not include it after block of instructions 1 the program would not jump to the end of the switch selective block (}) and it would continue executing the rest of the blocks of instructions until the first appearance of the break instruction or the end of the switch selective block. This makes it unnecessary to include curly brackets { } in each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression evaluated. For example:
1 2 3 4 5 6 7 8 9 10 11 | switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> using namespace std; int main () { // local variable declaration: char grade = 'D'; switch(grade) { case 'A' : cout << "Excellent!" << endl; break; case 'B' : case 'C' : cout << "Well done" << endl; break; case 'D' : cout << "You passed" << endl; break; case 'F' : cout << "Better try again" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; return 0; } |