7.7 — Intro to loops and while statements

Introduction to loops

And now the real fun begins -- in the next set of lessons, we’ll cover loops. Loops are control flow constructs that allow a piece of code to execute repeatedly until some condition is met. Loops add a significant amount of flexibility into your programming toolkit, allowing you to do many things that would otherwise be difficult.

For example, let’s say you wanted to print all the numbers between 1 and 10. Without loops, you might try something like this:

While that’s doable, it becomes increasingly less so as you want to print more numbers: what if you wanted to print all the numbers between 1 and 1000? That would be quite a bit of typing! But such a program is writable in this way because we know at compile time how many numbers we want to print.

Now, let’s change the parameters a bit. What if we wanted to ask the user to enter a number and then print all the numbers between 1 and the number the user entered? The number the user will enter isn’t knowable at compile-time. So how might we go about solving this?

While statements

The while statement (also called a while loop) is the simplest of the three loop types that C++ provides, and it has a definition very similar to that of an if statement:

while (condition)

A while statement is declared using the while keyword. When a while statement is executed, the condition is evaluated. If the condition evaluates to true, the associated statement executes.

However, unlike an if statement, once the statement has finished executing, control returns to the top of the while statement and the process is repeated. This means a while statement will keep looping for as long as the condition evaluates to true.

Let’s take a look at a simple while loop that prints all the numbers from 1 to 10:

This outputs:

1 2 3 4 5 6 7 8 9 10 done!

Let’s take a closer look at what this program is doing. First, count is initialized to 1, which is the first number we’ll print. The condition count <= 10 is true, so the statement executes. In this case, our statement is a block, so all the statements in the block will execute. The first statement in the block prints 1 and a space, and the second increments count to 2. Control now return back to the top of the while statement, and the condition is evaluated again. 2 <= 10 evaluates to true, so the code block is executed again. The loop will repeatedly execute until count is 11, at which point 11 <= 10 will evaluate to false, and the statement associated with the loop will be skipped. At this point, the loop is done.

While this program is a bit more code than typing all the numbers between 1 and 10, consider how easy it would be to modify the program to print all the numbers between 1 and 1000: all you'd need to do is change count <= 10 to count <= 1000.

While statements that evaluate to false initially

Note that if the condition initially evaluates to false, the associated statement will not execute at all. Consider the following program:

The condition 15 <= 10 evaluates to false, so the associated statement is skipped. The program continues, and the only thing printed is done!.

Infinite loops

On the other hand, if the expression always evaluates to true, the while loop will execute forever. This is called an infinite loop. Here is an example of an infinite loop:

Because count is never incremented in this program, count <= 10 will always be true. Consequently, the loop will never terminate, and the program will print "1 1 1 1 1"... forever.

Intentional infinite loops

We can declare an intentional infinite loop like this:

The only way to exit an infinite loop is through a return statement, a break statement, an exit statement, a goto statement, an exception being thrown, or the user killing the program.

Here's a silly example demonstrating this:

This program will continuously loop until the user enters n as input, at which point the if statement will evaluate to true and the associated return 0; will cause function main() to exit, terminating the program.

It is common to see this kind of loop in web server applications that run continuously and service web requests.

Best practice

Favor while(true) for intentional infinite loops.

Loop variables

Often, we want a loop to execute a certain number of times. To do this, it is common to use a loop variable, often called a counter. A loop variable is an integer that used to count how many times a loop has executed. In the examples above, the variable count is a loop variable.

Loop variables are often given simple names, such as i, j, or k. However, if you want to know where in your program a loop variable is used, and you use the search function on i, j, or k, the search function will return half your program! For this reason, some developer prefer loop variable names like iii, jjj, or kkk. Because these names are more unique, this makes searching for loop variables much easier, and helps them stand out as loop variables. An even better idea is to use "real" variable names, such as count, or a name that gives more detail about what you're counting (e.g. userCount).

Loop variables should be signed

Loop variables should almost always be signed, as unsigned integers can lead to unexpected issues. Consider the following code:

Take a look at the above example and see if you can spot the error. It's not very obvious.

It turns out, this program is an infinite loop. It starts out by printing 10 9 8 7 6 5 4 3 2 1 blastoff! as desired, but then goes off the rails, and starts counting down from 4294967295. Why? Because the loop condition count >= 0 will never be false! When count is 0, 0 >= 0 is true. Then --count is executed, and count wraps around back to 4294967295 (Assuming 32-bit integers). And since 4294967295 >= 0 is true, the program continues. Because count is unsigned, it can never be negative, and because it can never be negative, the loop won't terminate.

Best practice

Loop variables should be of type (signed) int.

Doing something every N iterations

Each time a loop executes, it is called an iteration.

Often, we want to do something every 2nd, 3rd, or 4th iteration, such as print a newline. This can easily be done by using the modulus operator on our counter:

This program produces the result:

01 02 03 04 05 06 07 08 09 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

Nested loops

It is also possible to nest loops inside of other loops. In the following example, the inner loop and outer loop each have their own counters. However, note that the loop expression for the inner loop makes use of the outer loop's counter as well!

This program prints:

1 2
1 2 3
1 2 3 4
1 2 3 4 5

Quiz time

Question #1

In the above program, why is variable inner declared inside the while block instead of immediately following the declaration of outer?

Show Solution

Question #2

Write a program that prints out the letters a through z along with their ASCII codes. Hint: to print characters as integers, you have to use a static_cast.

Show Solution

Question #3

Invert the nested loops example so it prints the following:

5 4 3 2 1
4 3 2 1
3 2 1
2 1

Show Solution

Question #4

Now make the numbers print like this:

      2 1
    3 2 1
  4 3 2 1
5 4 3 2 1

Hint: Figure out how to make it print like this first:

X X X X 1
X X X 2 1
X X 3 2 1
X 4 3 2 1
5 4 3 2 1

Show Solution

7.8 -- Do while statements
7.6 -- Goto statements

74 comments to 7.7 — Intro to loops and while statements

  • gel24

    what is the input of this one . can you help me please ? :(

    Enter starting number: 5
    How many number to display: 4
    5 = 25
    6 = 36
    7 = 49
    8 = 64

  • JustACPlusPluser

    I posted the following code into MS Visual C++ 2010 Express:

    #include "stdafx.h"
    #include "stdafx.h"
    using namespace std;

    int iii = 3;
    while (iii < 10)
    cout << iii << " ";
    cout << "done!";

    And the while statement says it "expected a declaration", plus when I try to compile, it gives me a bunch of errors about a missing semicolon. Please help ASAP,


    • omril

      Did you leave out all the necessities to spare room ?

      if you didn't to compile it you'll need to paste:

      #include "stdafx.h" // for MS visual Studio

      int main()

      using namespace std;

      int iii = 3;
      while (iii < 10)
      cout << iii << " ";
      cout << "done!";

  • mac

    from left to right up, and also downwards.....

  • mac

    what is the input of this one and also the reverse, using the for loop ,pls help asap

  • kakatu

    I have a problem with my assignment. Can you help me, please?
    Here is the assignment:
    to make telephone numbers easier to remember, some companies use letters to show their telephone number.for example using letters,the telephone number 438-5626 can be shown as GET some cases, to make a telephone number meaningful, companies might use more than seven letters. for example,225-5466 can be displayed as CALL HOME, which uses 8 letters. write a program that prompts the user to enter a telephone number expressed in letters and output the corresponding telephone number in digits. if the user enter more than seven letters then process only the first seven letters. also output the -(hyphen) after the third digit. allow the user to use both uppercase and lowercase letters as well as spaces between word.moreover, your program should process a many telephone numbers as the user wants. (the program must use while statement)

  • Barbarababy

    I have tried the following, what's wrong in it?

    # include
    # include

    using namespace std;

    int main()
    double prev_pos = 0;
    double current_pos,
    double prev_vel = 0;
    double current_vel,

    change_pos = current_pos - prev_pos;
    change_vel = current_vel - prev_vel;
    current_vel = avg_vel - prev_vel;
    avg_vel = change_pos / time_int;
    avg_acc = change_vel / time_int;

    cout << "Motion Analysis" << endl;
    cout << endl;

    // ask the user to enter a time interval in second

    cout <> time_int;
    cout << endl;
    cout <= 0 )
    cout <> current_pos;
    cout << endl;
    cout << "Average velocity (this interval): "
    << avg_vel << " feet/second" << endl;
    cout << endl;
    cout << "Average Acceleration: "
    << avg_acc << " feet/second/second" << endl << endl;

    if ( current_pos < prev_pos )
    cout << "Invalid value: " << current_pos;
    cout << " is less than the current position of " << current_pos;
    cout << ". Try again.";
    cout << endl << endl;
    cout << current_pos;
    cout << endl << endl;

    cout << endl;
    system ("pause");
    return 0;

  • Barbarababy

    Hi Alex, I have a problem with my assignment. Can you help me, please? Here is the assignment:

    Write a program that will analyze the data from a physics experiment.
    The data consists of a series of position measurements for a moving object. The position measurements will be entered by the user of the program as they are continually prompted. Each of the position measurements that the user enters will have been recorded at uniform time intervals. This time interval will be entered by the user when the program begins and will be followed by the series of position measurements. Each position should be greater than or equal to the previous position because the object is either moving in one direction or still, but never moving backwards. Therefore a negative position measurement will be used to signal the end of the user's data for the run of the program.
    After each of the position measurements has been entered, calculate and display the following:
    1. the average velocity for the time interval
    2. the average acceleration for the time interval
    Use the following formulas for the calculations:
    change of position = current position - previous position

    change of velocity = current velocity - previous velocity

    average velocity = change of position / time interval

    average acceleration = change of velocity / time interval
    1. The starting position and starting velocity should both be 0.
    2. There should be a loop to validate the position entered by the user. As stated earlier, each position that the user enters must be greater than or equal to the previous position. Each time the user enters an invalid position, an error message that includes the invalid position as well as the previous valid position should be displayed and the user should be given a chance to enter the current position again.
    Processing Requirements
    1. At the top of the C++ source code, include a documentation box that resembles the ones from programs 1 and 2.
    2. The program should be fully documented.
    3. Use meaningful variable names.
    4. Make sure and test the program with values other than the ones in the Sample Output.
    5. Hand in a copy of the source code using Blackboard.
    Sample Output
    Motion Analysis

    Enter the uniform time interval in seconds: 2.5

    Enter a position in feet (negative value to quit): 2

    Average velocity (this interval): 0.80 feet/second
    Average acceleration: 0.32 feet/second/second

    Enter a position in feet (negative value to quit): 5

    Average velocity (this interval): 1.20 feet/second
    Average acceleration: 0.16 feet/second/second

    Enter a position in feet (negative value to quit): 4

    Invalid value: 4 is less than the current position of 5. Try again.

    Enter a position in feet (negative value to quit): 12

    Average velocity (this interval): 2.80 feet/second
    Average acceleration: 0.64 feet/second/second

    Enter a position in feet (negative value to quit): -1

    Thank you very much!

  • polabonez

    I really just wanted to create an account, log in, just to post a thank you for this all. I have been attempting to teach myself as with a full time job I don't have time to go to school. I have a lot to learn, but just the detail you have gone into so far has been amazing.

    Thank again.

  • output should b

  • Radek

    Don't forget that infinite loops like

    while(true) {

    is usually used in web servers!

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">