While Loop in C++
A while loop is used to repeatedly execute a block of code as long as a given condition is true. It is also called an entry-controlled loop because the condition is checked before the execution of the loop body.
Syntax of While Loop:
while(condition)
{
// code to be executed
}
How While Loop Works?
Algo of while loop
- First, the condition is checked.
- If the condition is true, the loop body executes.
- Inside the loop, the loop variable is updated (increment or decrement).
- After updating, the condition is checked again.
- This process continues until the condition becomes false.
- When the condition becomes false, the loop stops.
Note: If the loop variable is not updated (e.g., missing increment or decrement like i++), the loop will run forever, which is called an infinite loop.
Program 1: Sum of First 5 Natural Numbers
#include <iostream>
using namespace std;
int main() {
int i = 1, sum = 0;
while(i <= 5) {
sum += i;
i++;
}
cout << "Sum = " << sum;
return 0;
}
Output:
Sum = 15
Explanation:
- The variable i is initialized to 1 and sum is initialized to 0.
- The while loop starts and checks the condition i ≤ 5.
- Since the condition is true, the loop body executes.
- Step 1: i = 1, sum = 0 → sum = sum + i = 0 + 1 = 1
- Step 2: i = 2, sum = 1 → sum = sum + i = 1 + 2 = 3
- Step 3: i = 3, sum = 3 → sum = sum + i = 3 + 3 = 6
- After each step, the value of i is increased using i++.
- This process continues until i becomes 6, making the condition false.
- Finally, the loop stops and the total sum (15) is displayed.
Program 2: Factorial of a Number
#include <iostream>
using namespace std;
int main() {
int n = 5;
int fact = 1;
int i = 1;
while(i <= n) {
fact = fact * i;
i++;
}
cout << "Factorial = " << fact;
return 0;
}
Output:
Factorial = 120
Explanation:
- The variable n is initialized to 5.
- fact is initialized to 1 (because factorial starts from 1).
- The loop runs from i = 1 to i ≤ n.
- Step 1: i = 1 → fact = 1 * 1 = 1
- Step 2: i = 2 → fact = 1 * 2 = 2
- Step 3: i = 3 → fact = 2 * 3 = 6
- Step 4: i = 4 → fact = 6 * 4 = 24
- Step 5: i = 5 → fact = 24 * 5 = 120
- After each step, i is increased using i++.
- When i becomes 6, the condition becomes false and the loop stops.
- Finally, the factorial value (120) is displayed.
Summary:
- While loop repeats code while condition is true.
- Condition is checked before execution.
- Always update the variable to avoid infinite loop.