While Block
Published by
sanya sanya
In C++, a "while" loop is a control flow statement that repeatedly executes a block of code as long as a certain condition remains true. It is used when you want to iterate over a block of code an indefinite number of times until the condition becomes false.
Syntax:
while (condition) {
// Code block to be executed
}
The condition is checked before each iteration, and if it evaluates to true, the code block is executed. If the condition becomes false, the loop is terminated, and the program continues with the next statement after the loop.
Example that demonstrates the usage of a while loop to print the numbers from 1 to 5:
#include
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}
return 0;
}
Output:
1 2 3 4 5
A while loop is suitable when you want to repeat a block of code based on a condition that might change during the execution of the loop. Some common scenarios where a while loop is used include:
- Processing input until a specific condition is met.
- Implementing game loops where the game continues until a certain condition (e.g., game over) is reached.
- Executing code as long as a certain resource or condition remains available.
It's important to ensure that the condition in the while loop eventually becomes false to avoid infinite loops. You need to update the variables or conditions inside the loop body so that the condition can eventually evaluate to false and terminate the loop.
Library
WEB DEVELOPMENT
FAANG QUESTIONS