C++ while Loop

๐Ÿ”„ C++ while Loop

while loop ka use tab hota hai jab humein nahi pata ho ki loop kitni baar chalega, bas condition true rehni chahiye.


๐Ÿ”น 1. Syntax

while (condition) {
// code
}

๐Ÿ‘‰ Condition true rahegi tab tak loop chalta rahega.


๐Ÿ”น 2. Basic Example

int i = 1;

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

Output:

1 2 3 4 5

๐Ÿ”น 3. Print Even Numbers

int i = 2;

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


๐Ÿ”น 4. User Controlled Loop

int num;

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

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


๐Ÿ”น 5. Infinite while Loop โŒ

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

โš ๏ธ Condition kabhi false nahi hoti.

โœ” Controlled version:

while (true) {
if (condition) break;
}

๐Ÿ”น 6. while vs do-while

while do-while
Pehle condition check Pehle execute
0 ya more times At least once

๐Ÿ”น 7. Common Mistakes

int i = 1;
while (i <= 5); // โŒ extra semicolon
{
cout << i;
}

โœ” Correct:

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

๐Ÿ“Œ Summary

  • while loop condition-based hota hai

  • Entry-controlled loop

  • Infinite loop se bachein

  • Best jab iterations unknown ho

You may also like...