Table of contents | |
Syntax of C++ While Loop | |
How While Loop Works in C++ | |
Example of C++ While Loop | |
Using While Loop to Check User Input | |
Conclusion |
In programming, loops are used to execute a set of statements repeatedly until a particular condition is met. One such loop in C++ is the while loop. In this article, we will explore the concept of while loops in C++, including its syntax, working, and examples.
The syntax for a while loop in C++ is as follows:
while (condition) {
// code to be executed
}
The while loop works as follows:
Let's see an example of a 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++;
}
return 0;
}
1 2 3 4 5
The while loop can also be used to check user input until a valid value is entered. Let's see an example:
#include <iostream>
using namespace std;
int main() {
int num;
do {
cout << "Enter a positive integer: ";
cin >> num;
} while (num <= 0);
cout << "You entered: " << num;
return 0;
}
While loops in C++ are an essential tool for executing a set of statements repeatedly until a particular condition is met. We have learned the syntax and working of while loops and explored examples that demonstrate their use. With practice, you can master the use of while loops in your programming projects.
70 videos|45 docs|15 tests
|
|
Explore Courses for Software Development exam
|