In C++, the while
loop is used to execute a block of code repeatedly as long as a certain condition is true. The basic syntax of a while loop in C++ is as follows:
while (condition) {
// code to be executed
}
The condition
is an expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. After the code is executed, the condition is evaluated again. If it is still true, the loop continues to execute, otherwise, the loop terminates and the control passes to the next statement after the loop.
Here's an example of a while loop in C++ that prints the numbers from 1 to 5:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << endl;
i++;
}
return 0;
}
In this example, the condition
is i <= 5
. The loop executes as long as the value of i
is less than or equal to 5. Inside the loop, the value of i
is printed and then incremented by 1 using the i++
statement.
The output of this program will be:
1 2 3 4 5
Comments
Post a Comment