By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,553 Members | 1,041 Online
Bytes IT Community

C++ and Loops

By John Bourbonniere
Developer, PlayZion.com

A C++ Tutorial - Loops

Loops allow programmers to repeat one or more statements a bunch of times. There are three main kinds of loops: for loops, while loops, and do loops.

FOR LOOPS

for (<initialization>; <stopping condition>;
<expression) {
<one or more statements>
} //end for

The <initialization> portion is often used to set the value of a counter variable. The <expression> is typically used to increment the counter variable. The for loop continues executing the statements it contains until the <stopping condition> is met.

The <stopping condition> may be a boolean expression which evaluates to true or false, or it actually may be an expression which produces any value. In the latter case, this value is converted to an integer. If this integer is 0, then the <stopping condition> is considered to be false. If this integer is not 0, the <stopping condition> is considered to be true.

For example,

int count, num, total = 0;
for (count = 1; count <= 10; count++) {
cout << "Enter integer #" << count << ": ";
cin >> num;
total = total + num;
} //end for

Note: The "++" operator adds one to a number, so count++; is equivalent to count = count + 1

WHILE LOOPS

while (<stopping condition>) {
<one or more statements>
} end while

The while loop checks to see if the <stopping condition> is true (or not -). If so, the statements inside the while loop are executed, then the <stopping condition> is checked again, and so on. When the <stopping condition> is found to be false (or -), execution continues with whatever statements follow at the end of the while loop.

For example,

int total = 0, num = 999;
while (num != 0) {
cin >> num;
total = total + num;
}

DO LOOP

do {
<one or more statements>
} while (<stopping condition>)

The do loop is similar to the while loop, except that it checks the <stopping condition> after the statements that it contains. This means that the statements inside a do loop are always executed at least once, whereas the statements inside a while loop may never be executed.