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:
while (condition) {
// Code to be executed as long as the condition is true
}
#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++.
#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
question2