C++ while loop
Created By: chatGPT
While loops are control flow statements that allow code to be executed repeatedly based on a given Boolean condition. In C++, the
while
loop checks the condition before executing the loop's body. Here's a simple structure of a while loop:while (condition) {
// Code to execute repeatedly
}
Let's look at an example where we want to print numbers from 1 to 5 using a while loop. We'll initialize a variable, check the condition, and print the number while incrementing it in each iteration.
int number = 1;
while (number <= 5) {
std::cout << number << std::endl;
number++;
}
In this code snippet, we start with
number
set to 1. The loop continues as long as number
is less than or equal to 5. After printing the value of number
, we increment it by 1 in each iteration, which eventually leads the loop to terminate once number
exceeds 5.#include <iostream>
int main() {
int number = 1;
while (number <= 5) {
std::cout << number << std::endl;
number++;
}
return 0;
}
While using loops, especially in real-world applications, it's important to ensure that the loop will eventually terminate. Failing to do so might lead to an infinite loop, which can freeze a program or consume system resources excessively.
// Infinite while loop example (be careful)
while (true) {
std::cout << "This will run forever!" << std::endl;
}
To prevent infinite loops, one common approach is to carefully manage your loop condition and ensure that a variable that affects the condition is correctly modified within the loop. Here's how you might do that:
int count = 0;
while (count < 10) {
std::cout << "Count: " << count << std::endl;
count++;
}