While Loop in C++
In this tutorial, we will learn about while loop in C++. We will cover the basics of iterative execution using while loops.
What is a While Loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop runs as long as the condition evaluates to true.
Syntax
The syntax for the while loop in C++ is:
while (condition) {
// Code block to be executed
}
The while loop evaluates the condition before executing the loop's body. If the condition is true, the code block inside the loop is executed. This process repeats until the condition becomes false.
Example 1: Printing Numbers from 1 to 5
- Declare an integer variable
i
. - Initialize
i
to 1. - Use a while loop to print numbers from 1 to 5.
C++ Program
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}
return 0;
}
Output
1 2 3 4 5
Example 2: Calculating the Sum of First N Natural Numbers
- Declare two integer variables:
n
andsum
. - Assign a value to
n
. - Initialize
sum
to 0. - Use a while loop to calculate the sum of the first
n
natural numbers. - Print the sum.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n = 10;
int sum = 0;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
cout << "Sum of first " << n << " natural numbers is " << sum;
return 0;
}
Output
Sum of first 10 natural numbers is 55
Example 3: Reversing a Number
- Declare three integer variables:
num
,rev
, anddigit
. - Assign a value to
num
. - Initialize
rev
to 0. - Use a while loop to reverse the digits of
num
. - Print the reversed number.
C++ Program
#include <iostream>
using namespace std;
int main() {
int num = 12345;
int rev = 0;
while (num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
cout << "Reversed number is " << rev;
return 0;
}
Output
Reversed number is 54321