0
0
C++programming~5 mins

While loop in C++

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of instructions as long as a condition is true. It saves you from writing the same code many times.

When you want to keep asking a user for input until they give a valid answer.
When you want to count up or down until a certain number is reached.
When you want to keep checking if a task is done before moving on.
When you want to repeat an action but don't know in advance how many times.
Syntax
C++
while (condition) {
    // code to repeat
}

The condition is checked before each repetition.

If the condition is false at the start, the code inside the loop will not run at all.

Examples
This prints numbers 1 to 5 by increasing count each time.
C++
int count = 1;
while (count <= 5) {
    std::cout << count << " ";
    count++;
}
This loop runs once because we set keepGoing to false inside.
C++
bool keepGoing = true;
while (keepGoing) {
    // do something
    keepGoing = false; // stop after one loop
}
Sample Program

This program prints numbers from 1 to 5, each on its own line, using a while loop.

C++
#include <iostream>

int main() {
    int number = 1;
    while (number <= 5) {
        std::cout << "Number: " << number << "\n";
        number++;
    }
    return 0;
}
OutputSuccess
Important Notes

Make sure the condition will eventually become false, or the loop will run forever.

You can use break; inside the loop to stop it early if needed.

Summary

A while loop repeats code while a condition is true.

The condition is checked before each repetition.

Use it when you don't know how many times you need to repeat in advance.