In the realm of C++ programming, loops play a crucial role in executing a set of instructions repeatedly until a particular condition is satisfied. The while loop stands out among these looping structures for its straightforward nature and flexibility.
In C++, a while loop is employed to repeat a section of the program multiple times. When the number of iterations is not predetermined, it is advisable to opt for a while loop over a 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's consider a basic illustration of a while loop to display numbers from 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 illustration, we display the integer values ranging from 1 to 10 by employing a while loop. Initially, we set an integer value as i=1. Subsequently, the loop evaluates the condition (1<=10). When the condition is met, it outputs the value of i. If the condition is not met, the loop is exited.
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++, it is possible to utilize a while loop within another while loop, referred to as a nested while loop. The nested while loop runs its course entirely each time the outer loop executes.
Simple Nested while Loop Example
Let's consider a basic illustration 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 have the option to establish an endless while loop by setting true as the conditional check. By utilizing true as the condition (while(true)) within the while loop, we can create a loop that runs infinitely.
Syntax:
It has the following syntax:
while(true)
{
//Block of the code
}
In this code structure, the loop will persist due to the perpetual truth of the condition.
Simple Example for Infinite While Loop
Let's consider a basic example to demonstrate the Infinite While Loop in C++.
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 bypasses the current iteration and proceeds to the next one.
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 plays a crucial role in iterating through actions when the iteration count is undetermined. Proficiency in while, do-while, and nested loops empowers programmers to craft adaptable and effective code. A solid grasp of loop termination, optimization strategies, and coding conventions can enhance program efficiency and sustainability.
Frequently Asked Questions
1. In C++ programming, which methods are used to terminate a while loop?
The conclusion of a while loop is determined by the following actions:
- The break statement promptly halts the loop iteration.
- Using a Return Statement not only concludes the function's execution but also terminates the loop process.
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 applied within loops using logical operators such as && and ||.
Example:
int x = 1, y = 10;
while (x <= 5 && y >= 6) { // Both conditions must be true
cout << x << " " << y << "\n";
x++;
y--;
}
The loop will keep running until the criteria x is less than or equal to 5 AND y is greater than or equal to 6 are satisfied.