The while loop in C++ is a control flow statement that allows code to be executed repeatedly based on a condition.
The loop continues to run as long as the condition evaluates to true, making it especially useful when the number of iterations is unknown in advance.
Syntax of the while Loop
while (condition) { // Code to execute as long as the condition is true }
- Condition: The loop checks this condition before each iteration. If true, the loop body executes; if false, the loop exits.
- The condition is evaluated before the loop body, making it a pre-test loop.
1. Basic while Loop Example
A simple while loop that prints numbers from 1 to 5.
#include <iostream> using namespace std; int main() { int i = 1; while (i <= 5) { cout << "i = " << i << endl; i++; } return 0; }
Explanation:
- The loop starts with i = 1.
- The condition i <= 5 is checked before each iteration. The loop prints i and then increments i by 1.
Output:
i = 1 i = 2 i = 3 i = 4 i = 5
2. Calculating the Sum of First n Numbers
A while loop can be used to calculate the sum of the first n positive integers.
#include <iostream> using namespace std; int main() { int n, sum = 0, i = 1; cout << "Enter a positive integer: "; cin >> n; while (i <= n) { sum += i; i++; } cout << "Sum of first " << n << " numbers: " << sum << endl; return 0; }
Explanation:
- The loop runs from i = 1 to n, adding each value to sum.
- After the loop, sum contains the total.
Sample Output:
Enter a positive integer: 5 Sum of first 5 numbers: 15
3. Using while Loop with User Input
The while loop is useful for repeatedly prompting the user until they enter a specific value.
#include <iostream> using namespace std; int main() { int password; while (true) { cout << "Enter the password (1234 to unlock): "; cin >> password; if (password == 1234) { cout << "Access granted!" << endl; break; } else { cout << "Incorrect password. Try again." << endl; } } return 0; }
Explanation:
- The loop continues until the user enters 1234.
- break exits the loop when the correct password is entered.
Sample Output:
Enter the password (1234 to unlock): 4321 Incorrect password. Try again. Enter the password (1234 to unlock): 1234 Access granted!
4. while Loop with Array Elements
A while loop can iterate through an array by incrementing an index variable until it reaches the array’s size.
#include <iostream> using namespace std; int main() { int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); int i = 0; while (i < n) { cout << "arr[" << i << "] = " << arr[i] << endl; i++; } return 0; }
Explanation:
- The loop continues as long as i is less than the array’s size, printing each element.
Output:
arr[0] = 10 arr[1] = 20 arr[2] = 30 arr[3] = 40 arr[4] = 50
5. while Loop in Reverse
A while loop can be used to iterate in reverse by initializing a variable to a high value and decrementing it.
#include <iostream> using namespace std; int main() { int i = 5; while (i > 0) { cout << "i = " << i << endl; i--; } return 0; }
Explanation:
- The loop starts from i = 5 and decrements i until it reaches 0.
Output:
i = 5 i = 4 i = 3 i = 2 i = 1
6. Infinite while Loop
An infinite while loop continues indefinitely unless stopped by a break statement, condition, or external interrupt.
#include <iostream> using namespace std; int main() { while (true) { cout << "This loop runs forever!" << endl; break; // Comment this line to make the loop truly infinite } return 0; }
Explanation:
- while(true) creates an infinite loop. Adding break prevents the loop from running indefinitely.
Output:
This loop runs forever!
7. Using while Loop with break and continue
- break: Immediately exits the loop.
- continue: Skips the current iteration and moves to the next.
#include <iostream> using namespace std; int main() { int i = 1; while (i <= 10) { if (i == 5) { i++; continue; // Skips when i == 5 } if (i == 8) { break; // Exits the loop when i == 8 } cout << "i = " << i << endl; i++; } return 0; }
Explanation:
- continue skips printing when i is 5.
- break exits the loop when i is 8.
Output:
i = 1 i = 2 i = 3 i = 4 i = 6 i = 7
8. Nested while Loop
A while loop inside another while loop is known as a nested while loop. It’s useful for 2D data structures like matrices.
#include <iostream> using namespace std; int main() { int i = 1; while (i <= 3) { int j = 1; while (j <= 3) { cout << i << "," << j << " "; j++; } cout << endl; i++; } return 0; }
Explanation:
- The outer loop controls rows, and the inner loop controls columns.
Output:
1,1 1,2 1,3 2,1 2,2 2,3 3,1 3,2 3,3
9. Summing Digits of a Number
A while loop can be used to process each digit of a number by repeatedly dividing it by 10.
#include <iostream> using namespace std; int main() { int num, sum = 0; cout << "Enter a positive integer: "; cin >> num; while (num > 0) { sum += num % 10; // Adds the last digit to sum num /= 10; // Removes the last digit } cout << "Sum of digits: " << sum << endl; return 0; }
Explanation:
- num % 10 extracts the last digit.
- num /= 10 removes the last digit.
Sample Output:
Enter a positive integer: 12345 Sum of digits: 15
10. Summary Table of Common while Loop Uses
Use Case | Code Example | Description |
---|---|---|
Basic while loop | while (i <= n) { …; i++; } | Loops while a condition is true |
Sum of numbers | while (i <= n) sum += i; | Calculates sum of first n numbers |
User input validation | while (input != target) { … } | Repeats until user enters the target value |
Array iteration | while (i < n) cout << arr[i++]; | Accesses each element in an array |
Reverse iteration | while (i > 0) { …; i–; } | Loops in reverse order |
Infinite loop | while (true) { …; } | Continues indefinitely |
break and continue | while (…) { if (…) break; } | Controls loop flow with break and continue |
Nested loop | while (…) { while (…) { } } | Loop within a loop |
Process digits | while (num > 0) { … num /= 10;} | Processes each |
digit of a number |
Complete Example: Using while Loop for Multiple Tasks
This example combines several use cases of the while loop, including calculating a sum, processing array elements, and handling user input.
#include <iostream> using namespace std; int main() { // 1. Calculate the sum of the first 5 numbers int sum = 0, i = 1; while (i <= 5) { sum += i; i++; } cout << "Sum of first 5 numbers: " << sum << endl; // 2. Iterate over array elements int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); int j = 0; cout << "Array elements: "; while (j < n) { cout << arr[j] << " "; j++; } cout << endl; // 3. Validate user input int password; while (true) { cout << "Enter the password (1234 to unlock): "; cin >> password; if (password == 1234) { cout << "Access granted!" << endl; break; } else { cout << "Incorrect password. Try again." << endl; } } return 0; }
Sample Output:
Sum of first 5 numbers: 15 Array elements: 10 20 30 40 50 Enter the password (1234 to unlock): 4321 Incorrect password. Try again. Enter the password (1234 to unlock): 1234 Access granted!
The while loop in C++ is powerful and versatile, providing control over repetitive tasks and conditions.