Typical examples might be:
Typically, the set of actions to be repeated is placed within curly brackets, e.g.
{ // do this // and this // and this // etc. }
The term loop is often used to describe the notion that we perform the set of actions from top to bottom, then "loop" around back to the top to repeat them.
The test for whether or not to repeat the set of actions one more time is placed either at the top or the bottom, giving us the terms top tested loop or bottom tested loop.
The general layout is shown below (without the official C++ syntax for the tests at the top or bottom).
// top tested loop do we perform the set of actions or skip past the loop and continue with the rest of the program? { do this and this and this etc } <= here we go back to the test at the top | // bottom tested loop { do this and this and this etc } <= here we go back to the test at the top do we go back to the top to perform the actions again, or do we drop out of the loop and continue with the rest of the program? |
Note that bottom tested loops always perform the set of actions at least once, since they don't test to drop out until they get to the bottom of the loop. Top tested loops, on the other hand, could decide on the very first test to skip past the loop - thus the actions inside the loop might never get executed.
There are three types of control statement for repetition in C++: called while loops, do while loops, and for loops.
The do-while loops are bottom tested, the other two are top tested.
while loops
A while loop is a top tested loop with the format
while (condition) { // actions to repeat if the condition is TRUE }The example below prints out all the powers of 10 less than one million:
int power = 1; while (power < 1000000) { printf("%d\n", power); power = 10 * power; }
do-while loops
A do while loop is a bottom tested loop with the format
do { // actions to repeat } while (condition);Each time the condition evaluates to true it goes back to the top of the loop and runs through the actions one more time;
The example below keeps adding together numbers the user types in until they enter a 0:
float sum = 0; float userValue; do { printf("Enter a number to add to the total\n"); printf(" or enter 0 to quit\n"); scanf("%f", &userValue); sum = sum + userValue; } while (userValue != 0); printf("The sum was %g\n", sum);
for loops
For loops are a slightly more complex structure, usually used to process a specific set of numeric or character values.
They include an initialization statement, a test condition, and an update statement. For example, the loop below starts variable x at value 1, performs the body of the loop if x's current value is less than or equal to 10, and at the end of each pass through the body of the loop it adds one to x:
int x; for (x = 1; x <= 10; x = x + 1) { printf("%d\n", x); }This is exactly equivalent to the following while loop:
int x = 1; while (x <= 10) { printf("%d\n", x); x = x + 1; }
Nested loops
We can put loops inside other loops, e.g.
int x = 1; while (x < 5) { int y = 100;; while (y < 400) { int z = x + y; printf("%d, ", z); y = y + 100; } printf("\n"; x = x + 1; }Each time we go through the "outside" loop (the x loop above) we may go through the inside loop multiple times.
In the example above, for each value of x (1, 2, 3, and 4) we go through values 100, 200, and 300 for y. The effect of the code above would be printing
101, 201, 301, 102, 202, 302, 103, 203, 303, 104, 204, 304,
Single-line loops
There is one case in which you may omit the curly brackets around the actions to be repeated: when the actions consist of only a single statement. This is most common with simple for loops or simple while loops, for example:
int i; for (i = 0; i < 10; i++) printf("%d\n", i); // the for loop body is just one statement while (x < y) x = x * 2; // the while loop body is just one statement
Infinite loops
One of the problems with loops is ensuring our test condition can and does eventually stop the loop.
Loops that never stop are called infinite loops, and the only way to interrupt them is to kill the program (done in linux by holding down the control key and pressing c).
Common causes of infinite loops include:
while (x < y) { }
while (x < y); { x = x + 1; }In this case the compiler thinks you are creating a single-statement loop where the statement is simply the semi-colon! It thinks the section in curly brackets is something seperate, to be run after the while loop completes.
int x = 1; while (x != 10) { x = x + 2; // x will always be odd, // so can never equal 10 }
for (<initialisation>; <loop condition>; <update>) { <executable statements> }
int sum, sumsquares, nextval; sum = 0; sumsquares = 0; for (nextval = 7; nextval <= 50; nextval++) { sum = sum + nexval; sumsquares = sum + (nextval * nextval); } printf("%d %d\n", sum, sumsquares);
for (x = 3*y; x >= testblah(); x = x + 17) { z = zarb(y) + foo(x); }This says to make the first pass through the loop with the value of
x
set to 3*y
, exit the loop at the start of
any pass where the value of x
is greater than or equal to
the value returned by function testblah()
,
and on each pass through the loop add 17 to the value of x.
Within the loop body, on each pass through the loop, we set a new
value for variable z
, determined by the sum of
functions zarb
and foo
(as applied to variables
y
and x
respectively)
for (x = 3; x < 17; x++) { blah = blah + x; if (foo(y) < 7) x = x + 1; }This makes code very difficult to understand/predict, and hence difficult to debug, maintain, and modify.
for (int index = 1; index < 17; index++) { foo(index); }The variable index can only be accessed inside the for loop
for (int index = 23; index > 4; index = index - 2) { // do whatever }This executes the body of the loop on odd values from 23 down to 5
#include <cstdio> using namespace std; int main() { int nextint, num_ints, sum; printf("Please enter the number of integers"); printf(" in your list\n"); scanf("%d", &num_ints); sum = 0; for (int index = 1; index <= num_ints; index++) { printf("Please enter the next integer\n"); scanf("%d", &nextint); sum = sum + nextint; } printf("The total of the %d", num_ints); printf(" integers is %d\n", sum); }
while ( <Boolean expression> ) { <statements> }
// find the smallest power of 2 greater than y power = 1; while (power < y) { power = power * 2; } printf("%d is the smallest power of 2", power); printf(" which is greater than %d\n", y);Suppose
y == 7
, the following happens:
initialise power to 1 check 1 < 7, double power, check 2 < 7, double power, check 4 < 7, double power, check 8 < 7, exit loop perform printf statements
printf("Please enter a line of text"); printf(" and hit enter\n"); scanf("%c", &nextchar); while (nextchar != '\n') { if (isupper(nextchar)) { nextchar = char(int(nextchar) + 32); } else if (islower(nextchar)) { nextchar = char(int(nextchar) - 32); } printf("%c", nextchar); scanf("%c", &nextchar); } printf("\n");
// find the greatest common divisor of m and n printf("The GCD of %d and %d is ", m, n); // swap them if n is bigger than m if (m < n) swap(m, n); remainder = num1 % num2; while (remainder != 0) { num1 = num2; num2 = remainder; remainder = num1 % num2; } printf("%d\n", n);
// example 1 for (x = 13; x != 100; x = x+2) { printf("%d\n", x); }
// example 2 while (x = 1) { // do whatever x = x * 3; }
// example 3 printf("Enter two integer values\n"); scanf("%d", &x); scanf("%d", &y); while (y > 0) { printf("y is %d\n", x); y = y - x; }
// print a histogram using asterisks printf("Welcome to the histogram program.\n"); printf("Enter the integer length of each line,\n"); printf("enter a negative number when done.\n"); scanf("%d", &linelength); while (linelength >= 0) { for (int i=0; i- Care should be taken when choosing exit values to make sure it is not a value the user could legitimately want processed
- In the example above, zero would be a poor choice of sentinel because the user might actually want some zero-length (empty) lines
do { <statements> } while ( <loop condition> );
printf("Enter a series of integers, "); printf("0 to quit"\n"); sum = 0; do { scanf("%d", &number); sum = sum + number; } while (number != 0); printf("The sum is %d\n", sum);
do { printf("Please enter a month (as 1 - 12)"); printf("\n"); scanf("%d", &month); } while ((month < 1) || (month > 12));
do { printf("Please enter a numerator and denominator"); printf(" for the division operation\n"); scanf("%d %d", &numerator, &denominator); } while (denominator == 0); result = numerator / denominator;
while (x < y); for (int index=z; index>13; index--);
while (x = 1) {
for (int index=3; index<17; index++) sum = sum + index; printf("running total is "); printf("%d\n", sum);
// want to add numbers x .. y inclusive for (int index=x; index<y; index++) sum += index;
#include <cstdio> using namespace std; int sumsquares(int lower, int upper); int main() { int low, high, result; do { printf("Please enter two integers,"); printf(" low number first\n"); scanf("%d %d", &low, &high); } while (low > high); result = sumsquares(low, high); printf("The sum of the squares of values "); printf("%d through %d is ", low, high); printf("%d\n", result); } int sumsquares(int lower, int upper) { int sumsquares = 0; for (int index=lower; index<=upper; index++) { sumsquares += (index * index); } return(sumsquares); }
for (int index=3; index<37; index++) { y = foo(index); printf("%d\n", zarb(y)); }
while (!quit) { cmd = get_command(); if (cmd == 'q') quit = true; else process(cmd); }
do { printf("Please enter the next integer\n"); scanf("%d", &x); process(x); } while (x != 0);
// print out a set of grid coordinates for (int Xaxis = 0; Xaxis < 3; Xaxis++) { printf(" "); for (int Yaxis = 1; Yaxis < 9; Yaxis++) { printf("%d%d ", Xaxis , Yaxis); } printf("\n"); }The output from this is
01 02 03 04 05 06 07 08 11 12 13 14 15 16 17 18 21 22 23 24 25 26 27 28
for (x = 0; x < 5; x++) { printf("From %d we go: ", x); for (y = x; y < 6; y++ ) { printf("%d ", y); } printf("\n"); }For each value of x (outer loop) we go completely through the values of y (inner loop)
>From 0 we go 0 1 2 3 4 5 >From 1 we go 1 2 3 4 5 >From 2 we go 2 3 4 5 >From 3 we go 3 4 5 >From 4 we go 4 5
for (letter = 'A'; letter <= 'H'; letter++) { for (digit = 1; digit <= 8; digit++) { printf("%c%c ", letter, digit); } printf("\n"); }
A1 A2 A3 A4 A5 A6 A7 A8 B1 B2 B3 B4 B5 B6 B7 B8 C1 C2 C3 C4 C5 C6 C7 C8 D1 D2 D3 D4 D5 D6 D7 D8 E1 E2 E3 E4 E5 E6 E7 E8 F1 F2 F3 F4 F5 F6 F7 F8 G1 G2 G3 G4 G5 G6 G7 G8 H1 H2 H3 H4 H5 H6 H7 H8
bool quit = false; int lower = 0; int upper = 0; char cmd; while (!quit) { printf("Enter c to continue, anything else to quit\n"); scanf("%c", &cmd); if (cmd == c) { printf("Enter a new lower bound\n"); scanf("%d", &lower); printf("Enter a new upper bound\n"); scanf("%d", &upper); sum = 0; for (int index=lower; index<=upper; index++) { sum += index; } printf("Sum %d to %d", lower, upper); printf(" is %d\n", sum); } else quit = true; }
// user can enter q to quit, e to query if a number is // even or odd, or n to find out how many valid // questions have been asked so far while (!quit) { print_prompt(); // prints out the menu scanf("%c", &cmd); switch (cmd) { case 'e': case 'E': printf("Please enter your number"); printf("\n"); scanf("%d", &number); printf("%d is ", number); if ((number % 2) == 0) printf("even"); else printf << "odd"); printf("\n"); count++; break; case 'n': case 'N': count++; printf("This is valid question number"); printf("%d\n", count); break; case 'q'; case 'Q': quit = true; break; default: printf("Invalid command\n"); } }
// user can enter q to quit, e to query if a number is // even or odd, or n to find out how many valid // questions have been asked so far while (!quit) { print_prompt(); // prints out the menu scanf("%c", &cmd); switch (cmd) { case 'e': case 'E': printf("Please enter your number\n"); scanf("%d", &number); printf("%d is ", number); if ((number % 2) == 0) printf("even"); else printf("odd"); printf("\n"); count++; break; case 'n': case 'N': count++; printf("This is valid question number"); printf("%d\n", count); break; case 'q'; case 'Q': quit = true; break; default: printf("Invalid command\n"); } }
int main() { char cmd; bool quit = false; int count = 0; while (!quit) { print_prompt(); // prints out the menu scanf("%c", &cmd); switch (cmd) { case 'e': case 'E': even_num(count); break; case 'n': case 'N': question_num(count); break; case 'q'; case 'Q': quit = true; break; default: printf("Invalid command\n"); } } } void even_num(int &c) { int number; printf("Please enter your number\n"); scanf("%d", &number); printf("%d is ", number); if ((number % 2) == 1) printf("not"); printf(" even\n"); c++; } void question_num(int &c) { c++; printf("This is valid question number"); printf("%d\n", c); }
for (int x=0; int x<10; x++) { for (int y=0; int y<10; y++) { for (int z=0; int z<10; z++) { dataplot(x, y, z); } } }
for (int x=0; x<10; x++) { for (int y=0; y<10; y++) { if (x<5) { if ((y>x) && (y<10-x)) printf("*"); else printf(" "); } else { if ((y>x) || (y<10-x)) printf(" "); else printf("*"); } } printf("\n"); } ********* ******* ***** *** * * *** ***** ******* *********