while Loop

The while loop in C++ is used to repeatedly execute a block of code as long as a condition remains true. It is commonly used when the number of iterations is not known in advance.

What is a while Loop?

A while loop is a control statement that keeps running until its condition becomes false.

It is mainly used when:

  • The number of repetitions is unknown
  • A condition controls the loop
  • User input or runtime conditions are involved

Syntax of while Loop

while (condition) {
// code to execute
}

How while Loop Works

  1. The condition is checked
  2. If the condition is true, the loop body executes
  3. After execution, the condition is checked again
  4. The loop continues until the condition becomes false

Example of while Loop

#include <iostream>
using namespace std;

int main() {
int i = 1;

while (i <= 5) {
cout << i << endl;
i++;
}

return 0;
}

Output

1
2
3
4
5

Example: Sum of Numbers

#include <iostream>
using namespace std;

int main() {
int i = 1;
int sum = 0;

while (i <= 5) {
sum += i;
i++;
}

cout << "Sum = " << sum;

return 0;
}

Infinite while Loop

If the condition never becomes false, the loop runs forever.

while (true) {
cout << "Infinite Loop";
}

Always make sure the condition eventually becomes false.

Difference Between for and while Loop

  • for loop is used when the number of iterations is known
  • while loop is used when the number of iterations is unknown

Example with User Input

#include <iostream>
using namespace std;

int main() {
int number;

cout << "Enter a number (0 to stop): ";
cin >> number;

while (number != 0) {
cout << "You entered: " << number << endl;

cout << "Enter a number (0 to stop): ";
cin >> number;
}

return 0;
}

Why while Loop is Important

The while loop is important because it:

  • Handles unknown repetitions
  • Supports condition-based execution
  • Is useful for user-driven programs
  • Simplifies repetitive tasks
  • Is widely used in real-world applications

Real-Life Example

Think of filling water in a tank:

  • While the tank is not full, water continues filling
  • Once full, the process stops

This is similar to how a while loop works.

Conclusion

The while loop in C++ is a flexible and useful looping structure for repeating tasks based on conditions. It is widely used in programs where the number of iterations depends on runtime conditions or user input.

Home » C++ Fundamentals (Beginner Level) > Loops > while Loop