News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

C++ Tutorial – 11 – Loops

There are three looping structures available in C++, all of which are used to execute a specific code block multiple times. Just as with the conditional if statement, the curly brackets for the loops can be left out if there is only one statement in the code block.

While loop

The while loop runs through the code block only if its condition is true, and will continue looping for as long as the condition remains true. Bear in mind that the condition is only checked at the start of each iteration (loop).

int i = 0;
while (i < 10) { cout << i++; } // 0-9

Do-while loop

The do-while loop works in the same way as the while loop, except that it checks the condition after the code block. It will therefore always run through the code block at least once. Notice that this loop ends with a semicolon.

int j = 0;
do { cout << j++; } while (j < 10); // 0-9

For loop

The for loop is used to run through a code block a specific number of times. It uses three parameters. The first one initializes a counter and is always executed once before the loop. The second parameter holds the condition for the loop and is checked before each iteration. The third parameter contains the increment of the counter and is executed at the end of each iteration.

for (int k = 0; k < 10; k++) { cout << k; } // 0-9

The for loop has several variations. For starters, the first and third parameters can be split into several statements by using the comma operator.

for (int k = 0, m = 0; k < 10; k++, m--) { 
  cout << k+m; // 0x10
}

There is also the option of leaving out any one of the parameters.

for (;;) { 
  cout << "infinite loop";
}

Break and continue

There are two jump statements that can be used inside loops – break and continue. The break keyword ends the loop structure, and continue skips the rest of the current iteration and continues at the start of the next iteration.

for (int i = 0; i < 10; i++)
{
  break;    // end loop
  continue; // start next iteration
}

Goto statement

A third jump statement that may be useful to know of is goto, which performs an unconditional jump to a specified label. This instruction is generally never used since it tends to make the flow of execution difficult to follow.

goto myLabel; // jump to label
myLabel:      // label declaration
Recommended additional reading:
Sams - Teach Yourself C++ in One Hour a Day