Scroll Progress Bar

While Loop

In C++, a while loop is a control structure that allows to repeatedly execute a block of code as long as a specified condition is true. Here's the basic syntax of a while loop:

Program:

while (condition) {
    // Code to be executed as long as the condition is true
}
condition: A Boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop continues; if it's false, the loop terminates. Here's a simple example of a while loop that counts from 1 to 5:
Program:

#include <iostream>

int main() {
    int count = 1;

    while (count <= 5) {
        std::cout << count << " ";
        count++;
    }

    std::cout << std::endl;

    return 0;
}

In this example, the while loop continues executing as long as count is less than or equal to 5. Inside the loop, the value of count is printed, and then it is incremented with count++.

A few key points about while loops:
  • The loop condition is evaluated before each iteration, so if the condition is initially false, the loop won't execute at all.
  • It's important to ensure that the loop condition eventually becomes false to avoid an infinite loop.
  • it can use any valid Boolean expression as the loop condition.
  • it can have multiple statements inside the loop block enclosed within curly braces {}.
  • Here's another example of a while loop that reads numbers from the user until a negative number is entered:
Program:

#include <iostream>

int main() {
    int num;
    
    std::cout << "Enter positive numbers (enter a negative number to stop):" << std::endl;
    
    while (true) {
        std::cin >> num;
        
        if (num < 0) {
            break; // Exit the loop if a negative number is entered
        }
        
        std::cout << "entered: " << num << std::endl;
    }
    
    std::cout << "Loop finished." << std::endl;

    return 0;
}

In this example, the loop continues indefinitely (while (true)) until a negative number is entered by the user, at which point the break statement is used to exit the loop.

while loops are an essential part of C++ programming and are used for tasks that involve repetition or iteration, such as reading data from input, processing data, and performing various calculations until a specific condition is met.


question


answer

question2


answer2