Simple Looping Mechanisms

It is desirable to have a program to perform certain task repetitively a certain number of times, or as long as a certain condition remains true.

The portion of the program that executes a statement or a group of statements a number of times is called a loop.

C++ has 3 types of loop constructs: the while-loop, the do-while-loop, and the for-loop. We will discuss these loops here.

C++ has two useful unary operators: the increment operator ++ and the decrement operator -- which are often found in statements to control loops.

If n is an integer, then n++ increases the value of n by 1, and n-- decreases n by 1.

For example, the statements:

int n = -10, m = 1;
n++;
cout << "The value of n is changed to " << n << endl;
m--;
cout << "The value of m is changed to " << m << endl;

yield the following output:

The value of n is changed to -9
The value of m is changed to 0

The increment and decrement operators are often used inside a loop body to control the number of times the loop is repeated.

The "++" in the name C++ came from the increment operator, and it is used to state that C++ is better than C.

We will take a closer look at the increment and decrement operators a little later.