C++ while Loop Examples

🔄 C++ while Loop Examples

Neeche C++ while loop ke basic se advanced examples diye gaye hain, taaki aap concept ko achhe se samajh sako.


🔹 1. Print Numbers 1 to 5

int i = 1;

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

Output:

1 2 3 4 5

🔹 2. Print Even Numbers

int i = 2;

while (i <= 10) {
cout << i << " ";
i += 2;
}

Output:

2 4 6 8 10

🔹 3. Sum of Numbers (1 to 10)

int i = 1, sum = 0;

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

cout << sum;

Output:

55

🔹 4. User Input Until Condition Met

int num;

cout << "Enter number (-1 to stop): ";
cin >> num;

while (num != -1) {
cout << "You entered: " << num << endl;
cin >> num;
}


🔹 5. Reverse a Number

int num = 123, rev = 0;

while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}

cout << rev;

Output:

321

🔹 6. Count Digits in a Number

int num = 4567, count = 0;

while (num != 0) {
count++;
num /= 10;
}

cout << count;

Output:

4

🔹 7. Infinite Loop Example ❌

while (true) {
cout << "Hello";
}

⚠️ Stop condition missing.


🔹 8. while with Boolean Expression

bool run = true;
int i = 1;

while (run) {
cout << i << " ";
if (i == 5)
run = false;
i++;
}


❌ Common Mistake

while (i <= 5); // ❌ extra semicolon
{
cout << i;
}

📌 Summary

  • while loop condition-based hota hai

  • Initialization & increment zaroori

  • Infinite loops se bachein

  • Best jab iterations unknown ho

You may also like...