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 returns 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 is 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 developers 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.

Show Hint

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

412 comments to 7.7 — Intro to loops and while statements

  • toasted melon

    i think this might be a more simplified answer for question 4 based off what we learned so far if im wrong please tell me, why.

    • André Mark

      Yeah, this worked, this was very helpful for me to follow especially as I am new to JS, and C++ and learning as I go along by following more experienced jedi coders

  • toasted melon

    i think this might be a more condensed answer for question 4 based off what we learned so far. if I'm wrong please tell me.

  • tip

    In the intentional infinite loops, why should I favor

    as a best practice instead of putting directly the break condition in the while parenthesis?

    • bb

      Because that makes your intention clear. Otherwise people who read your code will wonder if you intended an infinite loop or you messed up.

  • Armando IG

    Hello, my solution for question #4 was different from the one showed up, it still worked but I would like some feedback on my code to see if it is less optimal than the target solution.
    Thanks in advance.

  • frog

    Hello, thanks for the tutorials. The number triangles were great exercises.

    This might not really matter, but wouldn't the example this lesson is using produce an extra whitespace (' ') at the right-end of each row just before new line ('\n')?

    If it matters, I suggest printing the inner variable first for each row and then start the loop which prints whitespace first and then the inner variable. Something like this:

  • Rwondo bislungo

    My solution for the excercise:

  • UnknownLearner

  • James C

    Single space in second example is using double quotes, may want to use single quotes.

  • Mynah

    Nested loops are hard :(

    • Alex

      Yeah, they definitely take some getting used to. Using a debugger and watching the loop execute can be helpful to understand what it's doing.

  • Evelyn Ann Grace

    my solution to question 2,3,4 are as follow

  • sjon85

    Lots of fun! This is my solution:

  • Ahmed

    bro you should've given us more examples about nested loops before the quiz, I currently feel so stupid because I couldn't solve the quiz within 20 mins and it's making me feel really disappointed and mad at myself.

  • johnnyp

    Using the ternary if statement for question 4

  • Ladyoftheroundtable

    Quick comment, but the hint on question 4 started visible to me. I figured it out before noticing, but only just. I think it would be better to leave it as a hidden hint for those that want to puzzle through a new way of formatting.

  • Deva_B.D.M.


    which one has better performance???

  • Rayyan Khan

    I found an elegant solution for question 3!

  • dodo

    Damn, i couldn't do it on my own, and spent nearly 15 minutes for understanding what the last quiz does. Impressive as it is, I'm feeling down for not being able to do it. The last time i stopped programming was also due to my inability to understand loops.

    • akithetsar

      Don't worry, loops are not easy to understand, I remember learning loops for the first time and it was not easy, I did understand how one loop works, but nested was a problem, I suggest you re-read this chapter one more time, then go to every code snippet where there is nested loops and try to go one statement and say out loud what it is doing(even for variable initialization, so you can understand why you initialize it before or inside the loop), do it 10 times, and if it still doesn't click, dw that doesn't mean you will never be good at programming, just continue until you get to for loops, then do the same thing above, if you still don't understand try this vid: it is an illustration of a nested loop i believe(didn't really watch it so i might be wrong). Hope this helps

    • Alex

      The debugger can be a useful educational tool here. If you set up watches on the loop variable(s) and then step through and watch the loop execute line by line, it will help give you some insight into what's going on.

    • Spectrillius

      Well, the way I see it, that's why there's a show solution button right?
      If you don't understand something with the information given, then there's no shame in hitting the show solution button, provided you understand it afterwards.
      Otherwise, I would review the lesson or previous lessons if they're relevant.

  • John

  • Roxana

    Hi, can I get some help. If I want to multiply the digits in a number input by the user and have as a result only one digit how to do it to get it right. I am thinking the below but something is not quiet there:

  • pickino

    hello! what if i put a assignment inside the condition of the while loop, since an assignment is not some expression that we can say is false or true, how the loop gonna handle this for exemple? :

    int a=5;
    int b;
    while (a=b)
    /*do something ..*/


    (by the way , i'm not intending to put an equality operator == )

  • Firas Saleh

    Here's my take on it.

    Suboptimal, but i think it's good to share the different versions. I still have a long way to go :))

  • nuth vireak

    Question #4
    Hello NASCARDRIVER or ALEX. Please check my code

  • nav

  • brainy

    Yikes I really overcomplicated that 2nd question.

  • Spero

    What a great quiz! It was tough and fun at the same time. My answer for Q4 was so different that I went back and looked at everyone else's answers just to see all the different things people came up with. Alex's is for sure the best but it's just so interesting to see all the different ways people think. Thanks for all that you do!

  • SuperNoob

    Hello NASCARDRIVER or ALEX! Could you recommend me a good website (like learncpp!) to learn data structure and algorithm?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]