In C++ programming language, loops are an important concept to iterate over a group of statements until a specific condition is met. While loop is one of the loops that is known for its simplicity and versatility.
In C++, a while loop is used to iterate a part of the program several times. If the number of iterations is not fixed, it is recommended to use a while loop than for loop.
Syntax
It has the following syntax:
while(condition){
//code to be executed
}
Where,
- Condition: It is an expression that checks the given condition. If the condition is true, the loop executes its body. If the condition is false, it exits the loop.
- Update Expression: It updates the loop variable value, whether it increments or decrements.
- Body: It is the main body of the program that contains a set of statements that would be executed until the condition remains true.
- Start
- Initialize a variable
- Check the loop condition
- If the condition is true: Execute the loop body Modify the variable Repeat condition check
- If the condition is false, exit the loop
- Execute the loop body
- Modify the variable
- Repeat condition check
Flow Diagram of While Loop
C++ While Loop Examples
Print integer value from 1 to 10 using While Loop
Let us take a simple example of a while loop to print number 1 to 10.
Example
#include <iostream>
using namespace std;
int main() {
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Explanation:
In this example, we print the integer value from 1 to 10 using a while loop. Here, we initialize an integer value (i=1). After that, it checks the condition (1<=10) in the loop. If the condition is true, it prints the value of i. If the condition is false, it exits the loop.
Factorial Number Program using While Loop:
Example
#include <iostream>
using namespace std;
int main() {
int n, fact = 1, i;
cout << "Enter a positive integer: ";
cin >> n;
i = n;
while (i > 1) // start a while loop
{
fact *= i; //It is equal to factorial = factorial * i
i--;
}
// print the factorial of a number to the console.
cout << "Factorial of " << n << " is: " << fact << endl;
return 0;
}
Output:
Enter a positive integer:
5
Factorial of 5 is:120
C++ Nested While Loop:
In C++, we can use a while loop inside another while loop, which is known as a nested while loop. The nested while loop is executed fully when the outer loop is executed once.
Simple Nested while Loop Example
Let us take a simple example of a nested while loop in C++.
Example
#include <iostream>
using namespace std; //using standard library
int main () {
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
cout<<i<<" "<<j<<"\n";
j++;
}
i++;
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Print Multiplication Table using While Loop in C++
Example
#include <iostream>
using namespace std;
int main() {
int start, end, num, i;
cout << "Enter the starting number: ";
cin >> start;
cout << "Enter the ending number: ";
cin >> end;
num = start;
while (num <= end) { // Outer loop for numbers
i = 1;
cout << "Multiplication Table of " << num << ":\n";
while (i <= 10) { // Inner loop for table
cout << num << " x " << i << " = " << num * i << endl;
i++;
}
cout << endl;
num++; // Move to the next number
}
return 0;
}
Output:
Enter the starting number: 2
Enter the ending number: 3
Multiplication Table of 2:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Multiplication Table of 3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
C++ Infinitive While Loop
We can also create an infinite while loop by passing true as the test condition. It means that if we pass the condition to true (while(true)) in the while loop, it would be an infinitive while loop.
Syntax:
It has the following syntax:
while(true)
{
//Block of the code
}
In this syntax, this loop will continue because the condition is always true.
Simple Example for Infinite While Loop
Let us take a simple example to illustrate the C++ Infinitive While Loop:
Example
#include <iostream>
using namespace std;
int main () {
while(true)
{
cout<<"Infinitive While Loop";
}
}
Output:
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Print pyramids using Infinite while loop in C++
Example
#include <iostream>
using namespace std;
int main() {
int i = 1, j;
while (true) { // Infinite while loop
j = 1;
while (j <= i) {
cout << "* ";
j++;
}
cout << endl;
i++;
// Breaking condition to avoid infinite execution
if (i > 5) {
break;
}
}
return 0;
}
Output:
*
* *
* * *
* * * *
* * * * *
Controlling While Loop Execution:
- Using break Statement:
The break statement immediately exits the loop.
Example
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 10) {
if (i == 5) {
break;
}
cout << i << "\n";
i++;
}
}
Output:
1
2
3
4
- Using continue Statement:
The continue statement skips the current iteration and moves to the next.
Example
#include <iostream>
using namespace std;
int main() {
int i = 1; //initialize variable i with value 1
while (i <= 10) //start while loop
{
if (i == 5) {
i++; //increment i to avoid an infinite loop
continue;
}
cout << i << "\n"; //print the value of i
i++; //increment I by 1
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Conclusion
In C++, the while loop is an essential tool for repeating actions in C++ when the number of iterations is unknown. Mastering while do-while and nested loops enables developers to write efficient and flexible programs. Proper understanding of loop termination, optimization techniques, and best practices can lead to better performance and maintainability in programming.
Frequently Asked Questions
1. In C++ programming, which methods are used to terminate a while loop?
The termination of a while loop occurs through these statements:
- The break command instantaneously ends the loop execution.
- Return Statement ends both the function execution and the loop operation.
2. List out the major components of a while loop.
A while loop consists of:
- Execution depends on the Boolean condition, which determines the loop termination.
- The loop body refers to multiple sequential statements that run continuously throughout conditional truth.
- A loop control variable functions to modify itself within the loop to make the expression condition false thus halting infinite loops.
3. What specific situations lead us to adopt while loops over for loops?
A while loop should be used whenever any of the following circumstances apply:
- The loop needs to run until an unknown number of times.
- The loop will persist execution until a particular condition fulfils the criteria (such as user input validation).
- During loop execution, the loop control variable receives updated values at its current position instead of receiving initial values at the starting header.
4. What are the pros and cons of using a while loop in C++?
Advantages:
- The loop becomes applicable for situations where the number of iterations remains unknown before execution starts.
- The code integrates easily because of its straightforward syntax.
- More efficient for input validation and event-driven loops.
Disadvantages:
- An improper update of loop conditions can turn into endless looping situations.
- The loop structure of while displays a lower structure than when you need a definite number of iterations.
- Large computer programs make it hard to detect infinite loops during debugging.
5. Does while loop accept multiple conditional checks?
Multiple conditions can be implemented in loops through logical operators (&&, ||).
Example:
int x = 1, y = 10;
while (x <= 5 && y >= 6) { // Both conditions must be true
cout << x << " " << y << "\n";
x++;
y--;
}
The loop continues execution until both values meet the conditions x ≤ 5 AND y ≥ 6.