C++ While Loop

In C++, a While Loop is a control flow statement that allows you to execute a block of code repeatedly until a specific condition becomes false.

The syntax for a While Loop is as follows:

while (condition) {
    // code to be executed

The code within the curly braces will be executed repeatedly as long as the condition in parentheses is true. The condition can be any expression that can be evaluated to either true or false, such as a comparison of variables or a function call that returns a Boolean value.

Here is an example of a While Loop that counts from 1 to 10:

#include <iostream>

int main() {
    int i = 1;
    while (i <= 10) {
        std::cout << i << " ";
    return 0;

In this example, the variable i is initialized to 1, and the While Loop executes as long as i is less than or equal to 10. The loop body consists of a single statement that prints the value of i and increments it by 1. The loop will repeat until i becomes greater than 10, at which point the condition will become false and the loop will terminate.

It’s important to be careful when using While Loops to avoid infinite loops, which occur when the condition never becomes false and the loop continues to execute indefinitely. To prevent this, make sure that the condition can eventually become false, and that any variables involved in the condition are updated within the loop body.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial