0
0
C++programming~3 mins

Why While loop in C++? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could tell the computer to keep doing something until you say stop, without writing the same code many times?

The Scenario

Imagine you want to count from 1 to 10 by writing each number on a piece of paper. Doing this by hand means writing each number one by one, which takes time and effort.

The Problem

Manually repeating the same action over and over is slow and boring. It's easy to lose track, make mistakes, or forget to stop at the right time.

The Solution

A while loop lets the computer repeat a task automatically until a condition is met, saving you time and avoiding errors.

Before vs After
Before
int i = 1;
cout << i << endl;
i = 2;
cout << i << endl;
// ... repeated until 10
After
#include <iostream>
using namespace std;

int main() {
    int i = 1;
    while (i <= 10) {
        cout << i << endl;
        i++;
    }
    return 0;
}
What It Enables

It makes the computer do repetitive jobs quickly and correctly without you writing the same code again and again.

Real Life Example

Counting how many people enter a room until it reaches full capacity, without having to check each person manually.

Key Takeaways

While loops repeat actions until a condition changes.

They save time and reduce mistakes in repetitive tasks.

They help automate counting, checking, and waiting tasks.