5.5 — While statements

The while statement is the simplest of the four loops that C++ provides, and it has a definition very similar to that of an if statement:

while (expression)

A while statement is declared using the while keyword. When a while statement is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the 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.

Let’s take a look at a simple while loop. The following program prints all the numbers from 0 to 9:

This outputs:

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

Let’s take a closer look at what this program is doing. First, count is initialized to 0. 0 < 10 evaluates to true, so the statement block executes. The first statement prints 0, and the second increments count to 1. Control then returns back to the top of the while statement. 1 < 10 evaluates to true, so the code block is executed again. The code block will repeatedly execute until count is 10, at which point 10 < 10 will evaluate to false, and the loop will exit.

It is possible that a while statement executes 0 times. Consider the following program:

The condition 15 < 10 immediately evaluates to false, so the while statement is skipped. The only thing this program prints 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 "0 0 0 0 0 ..." forever.

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.

Programs that run until the user decides to stop them sometimes intentionally use an infinite loop along with a return, break, or exit statement to terminate the loop. It is common to see this kind of loop in web server applications that run continuously and service web requests.

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 variable that is declared for the sole purpose of counting 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, naming variables i, j, or k has one major problem. 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! Many words have an i, j, or k in them. Consequently, a better idea is to use iii, jjj, or kkk as your loop variable names. 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.

It is best practice to use signed integers for loop variables. Using 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 overflows back to 4294967295. And since 4294967295 is >= 0, the program continues. Because count is unsigned, it can never be negative, and because it can never be negative, the loop won't terminate.


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

Because the loop body is typically a block, and because that block is entered and exited with each iteration, any variables declared inside the loop body are created and then destroyed with each iteration. In the following example, variable x will be created and destroyed 5 times:

For fundamental variables, this is fine. For non-fundamental variables (such as structs and classes) this may cause performance issues. Consequently, you may want to consider defining non-fundamental variables before the loop. This is another one of the cases where you might declare a variable well before its first actual use.

Note that variable count is declared outside the loop. This is necessary because we need the value to persist across iterations (not be destroyed with each iteration).

Often, we want to do something every n iterations, 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 loops 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

5.6 -- Do while statements
5.4 -- Goto statements

318 comments to 5.5 — While statements

  • Raffaello

    this lesson was really stressful, I had to read all the comments and write/analyze them to figure out the solution on question #3 and #4, and still didn't get them. are nested loops that common in c++ programming or programming in general? or these kinds of operations to make the console print out triangles like those?

  • M.J

    quiz #4.

  • koe

    Section headers have a typo, "Loop variables[/strong>" and "[section]Iteration".

    EDIT: what do you mean by "Because the loop body is typically a block,"? Under what conditions would it not be a block?

    • nascardriver

      Headers fixed, thanks!

  • Ahmed Alkanaq

    Pure while loops, two of which nested inside the outer one, and the variables are closely defined to their implementation:

  • Gabe

    Quiz 2

    Quiz 3
    Used example as template and modified

  • Dudz

    My answer for question #4

  • Dudz

    My answer for question3

  • Dudz

    My answer for question#2

  • Am

    I really like that almost everyone else's "solutions" have been quite unique, also huge thanks to the work that you've done and continue to do.

    I'm not sure if you intended to only have "Inner" and "Outer" variables but here is my solution:

    Initially I was thinking of using the "Inverse" variable and block to determine the spaces I would need to first print, then go to the "Inner" block and use that variable (which is based on outer/the current row) to both determine the remaining values to decrementally print them.

    But it kept only printing 1 value per line then going to the new line instead of printing the rest of the values. Which prompted me to use inverse to print the remainder of the values and use inner as the counter instead. Tried:

    But realized that every time "Inner" wanted to print its value, "Inverse" was also re-initiated and spaces added again which didn't work. So I had to move it outside to the "Outer" block so it can keep its value until a new row is started again. Luckily this solution also lets me change to how many rows I want formatted up to 9, so I'm quite happy with it. I'd love to hear your feedback and would love to learn what else you think could be improved from it.

    Thanks as always :)

    • nascardriver


      When you want a character, use single quotation marks (' ', not " "). Full quotes are strings, strings are more expensive than characters. Other than that your code is really good, keep it up :)

  • Michael Sneberger

    For Quiz #4 I assumed that since we are in the while lesson we should use while loops but no if statements so I came up with this:

  • Fabio Henrique

    Hi there,
    I came out with this solution to the last question, let me know what you guys think please ?!

    Thank you guys !

    • nascardriver

      You're not using the outer loop, it only ever runs 1 cycle. Otherwise the code is good :)

      • Fabio Henrique

        Thank you nascar! And you're right, the rows loop were just running once... a better way to do this would be like this then ?!

        And thank you and Alex for these tutorial series, they are the best I've found so far !

        • nascardriver

          Yep, that's it!
          Syntax highlighting works after refreshing the page if you edit your comment, you don't have to delete and re-post it.

          • Fabio Henrique

            kkkk thanks for the tip, I was so annoyed that after every word I changed the code formatted text was gone. Lesson learned now XD cheers !!

  • Hakeem A Thomas

    Out of all the quiz question before this chapter, question 2 stumped me. I had to look at the solution. What do you recommend to do better problem solving in this situation. I am trying to become a better programmer and thinker.

    • nascardriver

      Figure out where you're stuck, then read up on that topic.

      Let's dissect the question
      "Write a program that prints out the letters a through z along with their ASCII codes."

      What do we need?
      "Write a program" -> You know how to compile code and run the program.
      "that prints" -> std::cout
      "the letters a through z" -> You need a loop, because you want to repeat something. You also need to know about `char`.
      "ASCII codes" -> ASCII codes and conversion to int

      Out of these things, I assume you got stuck at the loop or the ASCII codes. ASCII and conversion to int was covered before, so you'd have to re-read lesson 4.11. Then there's the new loop, which was covered in this lesson. To make it work in the quiz, you'll have to remember that `char` is an integral type and you can compare them with < = >. If you don't remember that, you could have used the cast to int and compare the ints.

      • Hakeem

        I got stuck figuring out how to inverse the loop.  I was trying to figure out how to get inner to equal 5 but display correct output. Turns out I only had to replace inner with a variable that contained 5. I got confused about how I could do that. Then in the solution, I just needed outer to be the variable

  • Alixsep

    Hi nascardriver,

    I am learning c++ with your website, this is my 2nd comment here,
    I solved this lesson's quizzes at 5 A.M (by myself in 10 minutes).

    I slept at 5:30 AM and woke up at 6:00 A.M went to college.

    my college teacher thought us the for and while loops, and exactly asked the students the quiz 4 and I was able to solve it out of 90 students, very clean and exactly like your solution.

    but then he just destroyed my whole character, and he said I am an asshole for solving the question LIKE THAT (TOO CONFUSING), he literally attacked me for straight up 10 minutes, and said that I can never become a programmer. He made me really sad.

    He also said that whoever avoiding "using namespace std;" is an asshole.

    the other student cannot even say the difference of double and integer, they don't know what is static_cast, function prototypes, enum classes, scopes, and ...

    the college is skipping these lessons, and the students also retarded as fuck. Unfortunately I live in Iran, you may not believe but in all of them it is only me who can talk English a little bit.

    I love your website, My only hope is ya'll. Thanks for your help, You literally changed my life forever, I hope you bests man. I am really sad, please tell me something that can motivate me to learn programming and make enough money to migrate and get out of Iran, I hate here.

    • nascardriver

      That sounds like a horrible teacher. I'm not expecting teachers to be able to write good code, quite the opposite actually. But he shouldn't have demotivated you by telling you how bad your code was, he should've shown you how to improve it.

      Since your college covered for-loops, you should've used one, because you knew how many times to loop will run before you start it:

      A simple change that makes the code a lot easier. If your teacher wants you to do something, even if you know it's bad practice, just go along with it to get a good grade. This is unfortunate, because all other students will learn it wrong, but it doesn't sound like it's worth trying to convince your teacher otherwise. If you do your homework with friends, show them how it's done right before doing it teacher-style. The next time your teacher complains, your friends will know that he's at fault, not you.

      When you're done with college and you're looking for a job, you'll be happy that you learned cpp on your own. If that kind of teacher is common in your college or country, make sure you write projects that you can show companies you apply at as a reference so that they know you're not a student who "learned" c++ in college.

      I wish you to best of luck! If you have any coding questions, either from here or your college, don't hesitate to ask.

      • Alixsep

        nascardriver thanks you so much.
        yes and i will use your beloving website, i owe you bro, you helped me a lot. is deitel and deitel a good book to read after your website?

        • nascardriver

          I don't recommend books at all. They don't get updates, resulting in outdated content. If you want to read a book, choose a topic that doesn't change as quickly as a language, for example networking, threading, graphics, algorithms, etc.
          Then read about that topic online in the latest version of C++.

  • The final task seems so easy but it took me 3 days to solve it)))
    And here is solution. I'll really appriciate if there are any comments.

    • nascardriver

      Declare one variable per line for better readability. Use --prefix and ++prefix unless you need postfix. You can change line 11 to

      and remove `ch`.

      • kitabski

        nascardriver, thank you very much for your comments and suggestions!!!
        I want to make a small suggestion myself. I think it would be a good idea if while posting a quiz it will be indicated which operators are allowed to be used. I mean,  as in the task 4 of this unit i thought that solution should be based solely on while operator.
        Thank you once again!!!!
        And happy coming holidays!!!

  • Ryan

    Is it more preferable to write \n with double speech marks("\n") or single speech marks('\n) or does it not matter

    • nascardriver

      \n is a single character, so you should use single quotation marks '\n'.
      If you use normal quotation marks, "\n" is treated as a string and the function you pass it to (`std::cout <<`) has to determine its length. This is unnecessarily slow.

  • Daki


    Firstly, I would like to thank the author for coming up with these tutorials! Hopefully it's normal for me to struggle a little and taking quite some time to understand as someone completely new to programming.

    It took me some time to solve quiz 4 and I came up with a different solution. Would really appreciate it if I could receive some feedback on my code.

    • nascardriver

      Hello Daki!

      > Hopefully it's normal for me to struggle a little and taking quite some time
      It is. Once you learned a programming language, it's a lot easier to learn another.

      - Inconsistent formatting. Use your editor's auto-formatting feature.
      - Use single quotation marks for characters (' ' instead of " ", '\n' instead of "\n").
      - Line 17 and 19 should be swapped. `inner` doesn't change inside the loop, so the `if` always evaluates to the same value.
      - `inner` should be moved right above the inner loop. You can replace its use in line 19 (Which should be line 17) with `outer`.
      - `blank` doesn't do anything. You can do `std::cout << ' ';` in line 21.

      • Daki

        Hi nascardriver,

        Thank you so much for your feedback! I see where my mistakes are now.
        The usage of loops is still a little confusing for me but I think I'll get the hang of it once I have enough practice on them.

  • JamesWeb

    Hello my programm works, but I would like to know if there is any bad practice inside or something I could improve.

    • nascardriver


      - Initialize your variables with brace initializers. Brace initialization provides better type safety.
      - Use --prefix unless you need postfix--. Postfix operators are slower for large types.

  • Ethan.Apollo

    Wanted to say that, I'm not sure you realise this but you said "a better idea is to use iii, jjj, or kkk" accidental racism? Also thanks for these tutorials there very helpful!

  • Benur21

    Why in the while syntax there is a ";"? While's don't have ; at the end

    • potterman28wxcv

      It's not the while who has the ';', but the statement. I suppose that the actual statement here is "statement;" and not just "statement".

      • Benur21

        Usually instead of "statement" we use a block of statements between "{}". How many ';'s are there now?

        • potterman28wxcv

          As you just wrote it's not a statement then but a block of statements. So the comment is irrelevant since the author wrote about a statement, not a block of statements..

          If they meant a block of statements surely they would have written :


  • Parsa

    this is irrelevant to this topic, but can you output a function call using cout?

    And what does "CL.exe exited with code 2" mean?

    And how do I delay how many times the while statements execute every second or something? I know there is a function called sleep but I don't know how it works or how to use it.

    • > can you output a function call using cout

      > And what does "CL.exe exited with code 2" mean?
      You'll have to google for that one.

      > delay

      Don't use `Sleep`, it only exists on Windows.

      • Parsa

        Ok, thanks.

        Since it is a function it's not possible to use a 'using' statement to assign a different name for it.

        Is there a similar thing for functions?

        • What you said doesn't fit to your previous question. Can you show and example of what you want to do?

          • Parsa

            (except this doesn't work).

            • There's no real aliasing for functions, you can only copy the function pointer (Covered later).

              If `std::this_thread::sleep_for` wasn't overloaded (Also covered later), you could do

  • ceeEss

    here's how I did it.

  • I'm pretty shit at math, so - for the first time ever - I decided to put my humble programming skills to work on a real problem. Insofar as I can tell, the program is working as intended.

    So, bearing in mind that I'm working through these lessons sequentially, did I do anything wrong? Could I have written my code more efficiently or used better logic?

    Just so you know that I'm paying attention: I realize that goto statements aren't generally advisable, but I REALLY thought it was a good solution here, given the minor scope of the project, and the need to revisit the moment post-seed. I also realize that infinite loops aren't generally advisable, but again, I thought it fit the purpose.

    Please let me know if I'm mistaken. Once again, thanks @NascarDriver & @Alex, you guys are doing a service to humanity running this site.

    • - Line 13: Conditions are bools, use `while (true)`.
      - Don't use `time`, use `std::time`.
      - `123` is an int, `123u` is an unsigned int.
      - Don't use `goto`. Add another `while (true)` loop and break it if the answer is correct.
      - Line 22: No, it's not. It shouldn't even compile. Make sure you followed lesson 0.10 and 0.11. You can't initialize variables with a value read from `std::cin` without writing a wrapper function.
      - Line 11, 28: If you're using the initial value of a variable, explicitly initialize the variable to that value (0). This won't change anything in you program, but makes your code easier to follow.
      - Seed random number generators only once. If the user solves the quiz within 1 second, the same "random" numbers will be generated.

      > Could I have written my code more efficiently
      You're calculating `x * y` in every cycle of the `goto`. This is unnecessary, since neither `x` nor `y` changed their values.

  • Dhananjay Singh

    Hi, thanks for your tutorials I have a different solution to your last quiz question
    Can you just go through it and tell me your feedbacks.

    thank you both;

  • Ankit

    I had a different approach for the last question than the one given in the solution, can anyone tell me if it is a good practice to code like I have done below.


    int main()
        int outer = 1;
            int inner = 5;
                std::cout<< "  ";
                std::cout<<" "<<inner--;

    • Hi!

      Your solution is better, because it doesn't perform a comparison in ever cycle of the inner loop.

      * Initialize your variables with brace initialization.
      * Use --prefix unless you need postfix--.
      * Use single quotation marks for chars.
      * Missing return-statement.

      Please use code tags when posting code.

  • Napalm

    I had a feeling this would be wrong because of having those numbers in there. I didn't realise you could increment a char. I'll certainly remember now though so I guess I still learned :)

  • Harshitha.R

    Hello there , could anyone help me as to how this program works?
    #include <iostream>

    // Loop between 1 and 5
    int main()
        int outer = 1;
        while (outer <= 5)
            // loop between 1 and outer
            int inner = 1;
            while (inner <= outer)
                std::cout << inner++ << " ";

            // print a newline at the end of each row
            std::cout << "\n";

        return 0;

  • Miquel

    Hello again!

    I finished the last quiz and had a different solution then the ones I found here.
    It works as expected, but I'd love to know if there's I could do better or any potential dangerous habits.

    Again, thanks Alex and nascardriver for all the help! I'm having a great time learning here.

    • Hello!

      If you want to, you can merge line 12 into line 9.
      Line 16 and 19 should print chars. This allows @std::cout::operator<< to use an optimized version to print (Since it doesn't have to check the text's length when it's just a char).

  • Red Lightning

    --The code in question 4, am I the only one spotting magic numbers (5)?

Leave a Comment

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