C++ While

Learn 'while' loop in C++.

While Loop:

A 'while' loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. The basic syntax of a 'while' loop looks like this:

while (condition) {
    // code to be executed while the condition is true
}

Breakdown:

1. The 'condition' is evaluated first. If it is true, the code inside the loop is executed. If the condition is false initially, the code inside the loop will not execute at all.

2. After the code inside the loop is executed, the condition is checked again. If the condition is still true, the loop continues to execute, and the process repeats. If the condition becomes false, the loop terminates, and program control moves to the next statement after the loop.

Here's a example of a 'while' loop that prints numbers from 1 to 5:

cpp Copy Code
#include<iostream>

int main() {
    int i = 1;

    while (i <= 5) { 
        std::cout << i << " "; 
        i++; // increment the counter variable
    }

    return 0;
}

Explanation:

The loop will continue executing as long as the condition 'i <= 5' is true. The counter variable 'i' is incremented inside the loop to ensure that the loop eventually terminates.

Output:
1 2 3 4 5

Note: Be cautious when using 'while' loops to ensure that the condition eventually becomes false; otherwise, you may create an infinite loop that never terminates.

while (1) {...}

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.