Loading...

C++ while Loops

The for page ended with thirty-three lines on the screen, and the last one was 2, the final value that i printed inside for (int i = 0; i < 3; i++). This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. The for loop stays in the file. The new work adds a second loop after it: a while that counts down from 3. The screen grows to thirty-six lines, and the last three are 3, then 2, then 1.
This page continues the Control Flow module. The first loop tool was for, which packed start, test, and step into one header line. A while loop uses the same three ideas, but it spreads them out. The start sits on its own line above the loop. The test sits alone inside the parentheses after the word while. The step sits inside the braces with the body. That split is the point of this page, so you can see each job where it lives.
A program needs a loop like this when the stop depends on a value that the body itself changes, or when you want the start and the step written as ordinary lines you can read one at a time. A countdown is a clear example. You store a number, print it while it is still greater than zero, and subtract one after each print. The count is not locked into a for header. It is a normal int box that the body updates.

A while statement starts with the keyword while and a test in parentheses. The line while (n > 0) shows that shape. There is no start and no step inside those parentheses. Only the question belongs there: is n still greater than 0? The braces after the while line hold the body. In this file the body does two jobs on every pass. First it prints the current value of n. Then it runs n--;, which subtracts one from n and stores the result back in the same box.
The start runs once, before the loop begins. In this file the start is int n = 3;, written above the while line. Then the test runs before every pass, including the first. When the test is true, the body runs, including the step. When the test is false, the loop ends, and the program continues with the line after the closing brace. Walk the checked values. n starts at 3. The test n > 0 is true, so the body prints 3 and then stores 2. The test is still true, so the body prints 2 and then stores 1. The test is still true, so the body prints 1 and then stores 0. Now n > 0 is false, so the loop stops. Three new lines appear: 3, then 2, then 1.
The counter name is a choice. This file uses n, a short name that is not the same as the for index i still sitting above in the file. Keeping two names makes it easy to see which loop owns which box. The braces are required when the body has more than one statement, and this course always writes braces, even for one statement, so the print and the step stay together as one unit.

The three jobs must stay in their places. The start is not inside the parentheses. The step is not a second start above the loop. A common mistake is to leave n--; out of the braces. Then n stays at 3 forever, the test stays true, and the body prints 3 without stopping. Another common mistake is to put quotes around n on the print line, so the screen shows the letter n three times instead of the numbers. The print line in this file is std::cout << n << std::endl;, with no quotes around n, so the number appears.
The step n-- means the same thing as n = n - 1 for this page. Either form subtracts one after the body prints. The form n-- is short and common in C++ loops. The test uses >, not >=, so the body runs while n is 3, then 2, then 1, and stops when n becomes 0. If the test were n >= 0, the body would also run when n held 0, and a fourth line would appear. The bound in the test is the value that ends the loop when the comparison becomes false.
A while loop is the right tool when you want the start and the step written as ordinary lines, or when the stop depends on a value that the body updates in its own way. A for loop is still the right tool when the count is known up front and fits cleanly in one header. This page keeps both loops in the same file so you can compare them. It stops before the next control tools that leave a loop early. The next page names those tools once at the end.

Type the file in this order, or add only the new lines if types.cpp is already on disk. After the for loop that prints i, and before return 0;, add int n = 3; and the while loop with its braces, the print line for n, and n--;. The file name on disk stays types.cpp. The checked file is below, and the new lines are the n box, the while statement, the print inside its braces, and the step.

types.cpp adds a while countdown that prints 3, 2, and 1 after the for

cpp
#include <iostream>
#include <string>

int main()
{
    // the word stays pine
    std::string word = "pine";
    int count = 2;
    double ratio = 0.5;
    bool ready = true;
    double price = 7.9;
    const int limit = 10;
    int scores[3] = {4, 5, 6};
    std::string other = "cone";
    std::string joined = word + " " + other;
    int total = 17;
    int step = 3;
    step += 4;
    int score = 72;
    int goal = 50;
    bool wet = false;
    std::string result;
    int day = 3;
    std::string name;
    std::cout << word << std::endl;
    std::cout << count << std::endl;
    std::cout << ratio << std::endl;
    std::cout << ready << std::endl;
    std::cout << word.size() << std::endl;
    std::cout << joined << std::endl;
    std::cout << word[0] << std::endl;
    std::cout << joined.find("cone") << std::endl;
    std::cout << joined.substr(5, 4) << std::endl;
    std::cout << count * 4 << std::endl;
    std::cout << 7 / 2 << std::endl;
    std::cout << 7.0 / 2 << std::endl;
    std::cout << (count > 1) << std::endl;
    std::cout << (count == 3) << std::endl;
    std::cout << !ready << std::endl;
    std::cout << static_cast<int>(price) << std::endl;
    std::cout << static_cast<double>(count) / 4 << std::endl;
    std::cout << static_cast<int>(ratio * 3) << std::endl;
    std::cout << limit << std::endl;
    std::cout << limit * count << std::endl;
    std::cout << scores[0] << std::endl;
    std::cout << scores[2] << std::endl;
    std::cout << total % 5 << std::endl;
    std::cout << step << std::endl;
    std::cout << (score >= goal) << std::endl;
    std::cout << (score < goal) << std::endl;
    std::cout << ((score >= goal) && (count == 2)) << std::endl;
    std::cout << ((score < goal) || wet) << std::endl;
    if (score >= goal) {
        result = "pass";
    } else {
        result = "retry";
    }
    std::cout << result << std::endl;
    if (wet) {
        std::cout << "wet" << std::endl;
    }
    switch (day) {
        case 1:
            name = "mon";
            break;
        case 2:
            name = "tue";
            break;
        case 3:
            name = "wed";
            break;
        default:
            name = "other";
            break;
    }
    std::cout << name << std::endl;
    for (int i = 0; i < 3; i++) {
        std::cout << i << std::endl;
    }
    int n = 3;
    while (n > 0) {
        std::cout << n << std::endl;
        n--;
    }
    return 0;
}

Rebuild with g++ -std=c++17 types.cpp -o types, then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows thirty-six lines. The first thirty-three are the same as on the for page. The last three are 3, then 2, then 1, the values of n on each pass of the while.
Check the last three lines first. The loop started with n equal to 3, printed that value, stepped to 2, printed again, stepped to 1, printed again, and stopped when n became 0. The table gives each row its piece, so compare your run with it line by line. If the screen shows only thirty-three lines, the while block is missing or sits after return 0;. If the last three lines are the letter n, the print line has quotes around n. If the program never stops and keeps printing 3, the step n--; is missing from the braces.

📊 The while loop and what it shows

Piece What the screen shows
First 3, because n starts at 3 and the first pass prints that value
Last 1, because the body runs while n is greater than 0, so the last printed value is 1
Rule a while tests first, runs the body, and needs its step inside the braces
Screen pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, 20, 4, 6, 2, 7, 1, 0, 1, 0, pass, wed, 0, 1, 2, 3, 2, 1

Try one change at a time. Change while (n > 0) to while (n > 1), leave the start at 3, and rebuild. The last two lines become 3 and 2 only, because the body stops when n becomes 1. Put n > 0 back. Next, change the start from int n = 3 to int n = 4, leave the test as n > 0, and rebuild. The new lines become 4, then 3, then 2, then 1, because the first pass starts at 4. Put the 3 back. Each experiment changes one thing, so the screen shows exactly which part of the while setup caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
This page ends the second loop tool and stops before the next control tools. The next page is break-continue, which leaves a loop early or skips one pass without ending the whole loop. The while you have just written is the right shape when the start and the step belong on their own lines. You leave with thirty-six lines on the screen, and the last one is 1. Count the lines before you leave. There are thirty-six, and the last one is 1.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top