The while loop is a control flow statement in C++ that allows a block of code to be executed repeatedly as long as a certain condition is true. It is one of the most commonly used loops in C++ programming and is used to iterate over a block of code until a specific condition is met.
The syntax of the while loop in C++ is as follows:
while (condition) { // code to be executed }
The condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop is exited and the program continues with the next statement after the loop.
The while loop is useful when the number of iterations is not known in advance and depends on some condition. For example, it can be used to read input from a user until a specific value is entered, or to process data until a certain condition is met.
Here is an example of a while loop that prints the numbers from 1 to 10:
int i = 1; while (i <= 10) { std::cout << i << " "; i++; }
This code initializes a variable i to 1 and then enters a while loop. The condition i <= 10 is evaluated before each iteration of the loop. As long as i is less than or equal to 10, the code inside the loop is executed. The code inside the loop prints the value of i and then increments i by 1. This process continues until i is no longer less than or equal to 10.
The output of this code would be:
1 2 3 4 5 6 7 8 9 10
The while loop can also be used with boolean variables. For example, the following code uses a while loop to read input from the user until the user enters the word "quit":
std::string input; bool quit = false; while (!quit) { std::cout << "Enter a word (or 'quit' to exit): "; std::cin >> input; if (input == "quit") { quit = true; } else { std::cout << "You entered: " << input << std::endl; } }
This code initializes a string variable input and a boolean variable quit to false. It then enters a while loop that continues until quit is set to true. Inside the loop, the code prompts the user to enter a word and reads the input using std::cin. If the input is "quit", the code sets quit to true and exits the loop. Otherwise, it prints the input using std::cout.
The output of this code would be:
Enter a word (or 'quit' to exit): hello You entered: hello Enter a word (or 'quit' to exit): world You entered: world Enter a word (or 'quit' to exit): quit
In conclusion, the while loop is a powerful control flow statement in C++ that allows a block of code to be executed repeatedly as long as a certain condition is true. It is useful when the number of iterations is not known in advance and depends on some condition. By using boolean variables, it can be used to read input from the user until a specific value is entered or to process data until a certain condition is met.