While Loops
Lesson 20Author : Afrixi
Last Updated : November, 2022
While loops in C++ are used to execute a block of code repeatedly as long as a certain condition is true. Here’s an example of a program that uses a while loop to print the numbers from 1 to 10:
#include <iostream>
int main() {
int i = 1;
while (i <= 10) {
std::cout << i << std::endl;
i++;
}
return 0;
}
In this example, the program initializes a variable i
to 1, and then enters a while loop with the condition i <= 10
. The loop executes the code block inside the braces repeatedly as long as the condition is true. The code block simply prints the value of i
to the console using std::cout
, and then increments i by 1
using the ++
operator.
When i
reaches 11, the condition i <= 10
becomes false and the program exits the loop. Finally, the program returns 0 to indicate successful execution.