C++ Control Statement While Loop
The while loop in C++ is a control statement used to repeatedly execute a block of code as long as a condition is true. It checks the condition at the beginning of each iteration. If the condition is true, the block of code is executed and the program jumps back to the beginning of the loop to check the condition again. The loop continues until the condition evaluates to false.
Syntax
The syntax for the while loop in C++ is as follows:
while (condition) {
// Code to be executed while the condition is true
}
The condition is a logical expression that evaluates to either true or false. If the condition is true, the code inside the loop will be executed. If the condition is false, the loop will be exited and control will pass to the next statement in the program.
Example
#include <iostream>
int main() {
int count = 0;
while (count < 5) {
std::cout << "Count is: " << count << std::endl;
count++;
}
return 0;
}
Output
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Explanation
In the example above, we declare a variable count
and initialize it to 0. We then begin a while loop that will repeat as long as the condition count < 5
is true. Inside the loop, we print the value of count
to the console using std::cout
, and then increment it by 1 with count++
. This repeats until count
reaches 5, at which point the condition evaluates to false, and the loop is exited.
Use
The while loop is commonly used when you have a block of code that needs to be executed multiple times, but you don't know exactly how many times in advance. You can use a while loop to keep executing the code until a certain condition is met. You might use a while loop to read data from a file, process user input, or implement game logic, among other things.
Important Points
- Make sure to include a conditional statement in the while loop that will allow the loop to exit eventually.
- Be careful not to create an infinite loop by including a condition that never evaluates to false.
- The block of code inside the loop must modify the condition in some way to eventually lead to the exit of the loop.
- A while loop can be nested inside another while loop or any other control structure.
Summary
In this tutorial, we learned about the while loop in C++. We discussed its syntax, an example program, its output, explanation, uses, important points, and summary. The while loop is a powerful tool for repeating a block of code as long as a condition is true, and is commonly used in C++ programming.