Jump to content

C++/Loops

From Wikiversity
< C++

Loops allow a programmer to execute the k kisame block of code repeatedly. We will make heavy use of conditional statements in this section.k

The while Loop

[edit | edit source]

The while loop is really the only necessary repetition construct. The for loop, coming up, can be duplicated using a while loop, and with more control. A simple negation can perform the same behavior as an until loop.

The syntax is as follows:

while ( ''condition'' ) {
    //body
}

Again, the curly braces surrounding the body of the while loop indicate that multiple statements will be executed as part of this loop. If the actual code looked something like this:

while ( x == 4 )                   
    y += x;
    x += 1;

means

while ( x == 4 ) {
    y += x;
}
    x += 1;

There would be a problem. According to what was written, even though the second line after the while was indented, only the first line corresponds to the while loop. This is a huge problem because the variable involved in the condition (x) does not change, so it will always evaluate to true, making this an infinite loop. This could be alleviated by containing all statements intended to be a part of the loop body in { }.

while ( x == 4 ) {
    y += x;
    x += 1;
}

The do...while Loop

[edit | edit source]

The do...while loop is nearly identical to the while loop, but instead of checking the conditional statement before the loop starts, the do...while loop checks the conditional statement after the first run, then continuing onto another iteration.

The syntax is as follows:

do {
    //body
} while (''condition'');

As you can see, it will run the loop at least once before checking the conditional.

The do...while loop is still haunted by infinite loops, so exercise the same caution with the do...while loop as you would with the while loop. Its usefulness is much more limited than the while loop, so use this only when necessary.

The for Loop

[edit | edit source]

The for loop is a loop that lets a programmer control exactly how many times a loop will iterate.

The syntax is as follows:

for (expression for initialization ; expression for testing ; expression for updating) {
    //body
}

Here is an example of how the for loop works:

for ( int i = 0; i < 10; ++i ) {
    std::cout << i+1 << std::endl;
}

The code above and below are more or less equivalent.

int i = 0;
while ( i < 10 ) {
    std::cout << i+1 << std::endl;
    ++i;
}

What does this loop do? Prior to the first iteration, it sets the value of i to 0. Next, it tests (like a normal while loop) if i is less than 10. If the statement returns true, the body of the loop is run and the program will print the value returned by the simple arithmetic statement i+1 and move the terminal cursor down to the next line. After the loop is finished, i is incremented (by 1), as specified in the update statement, and the conditional is tested again.

So, this loop will run a total of 10 times, printing the "i+1" each time. You've taught your program to count!

The variable used in for loops is generally an integer variable named i, j, or k, and is often initialized prior to the beginning of the for loop. Another option is to initialize the variable at the same time that you declare the variable's initial state:

for (int i = 0; i < 10; i++) {
    std::cout << i+1 << std::endl;
}

If this is done properly, it is possible to nest for loops.

#include <iostream>
using namespace std;
int main(){
int input;

cout << "How many missiles will you fire?" << endl;
cin >> input;
cout << "\n";

for (int i = 0; i < input; i++) {
    for (int j = 10; j > 0; j--) {
       cout << j << " ";
    }
    cout << "Missile " << i+1 << " has launched." << endl;
}

cout << "All missiles have been launched." << endl;
return 0;
}


What does this program do? The user is prompted to choose an integer, which is used in the conditional statement of the first for loop. Each iteration of the i loop will cause the j loop to run, which counts down from 10 to 1 before allowing the i loop to continue. The output will look something like this:

How many missiles will you fire?
3
10 9 8 7 6 5 4 3 2 1 Missile 1 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 2 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 3 has launched.
All missiles have been launched.

Equivalence of C++ Looping Structures

[edit | edit source]

The while loop can take the place of do...while loops if the condition for the while loop is "rigged" to be true at least the first time around.

The while loop can take the place of until loops by negating the condition that would be specified for the until loop, as explained above.

For and While loops

[edit | edit source]

A for loop is structured as follows:

for (<initial expression> ; <condition> ; <update expression>) {
   <block of code>
}

This can easily be reformatted as (do recognize the extra enclosing brackets, and the two extra semicolons after the expressions in order to turn them into statements):

{
    <initial expression> ;
    while (<condition>) {
        <block of code>
        <update expression> ;
    }
}

A for loop is more often used in by C++ programmers due to its conciseness as well as its separation of the looping logic (often using a loop control variable like "int i" or another simple iterator) from the loop's content. A while loop is often preferred if the initial statement or update statement requires more complex code than fits neatly into the for construct. However, the two are fully equivalent therefore it is ultimately a coding style decision, not a technical decision whether to use one or the other.

Infinite Loops

[edit | edit source]

One common programming mistake is to create an infinite loop. An infinite loop refers to a loop, which under certain valid (or at least plausible) input, will never exit.

Beginning programmers should be careful to examine all the possible inputs into a loop to ensure that for each such set of inputs, there is an exit condition that will eventually be reached. In addition to preventing the program from hanging (i.e. never finishing), understanding all potential inputs and exit conditions demonstrates a solid understanding of the algorithm being written. Academic studies of programming languages often test students' ability to identify infinite loops for the very reason that doing so often requires a solid understanding of the underlying code.

Compilers, debuggers, and other programming tools can only help the programmer so far in detecting infinite loops. In the fully general case, it is not possible to automatically detect an infinite loop. This is known as the halting problem. While the halting problem is not solvable in the fully general case, it is possible to determine whether a loop will halt for some specific cases.

Example of Infinite loop

[edit | edit source]
#include <iostream>
int main()
{
  while(1) {
    // printf("Infinite Loop\n");
     std::cout << ("Infinite loop\n");
  }
  return 0;
}

This code will print infinite loop with out stopping.

Where To Go Next

[edit | edit source]
Topics in C++
Beginners Data Structures Advanced

Template loop detected: C++/Lessons/Beginners

Template loop detected: C++/Lessons/Data Structures

Template loop detected: C++/Lessons/Advanced

Part of the School of Computer Science