
Hello Ian, really nice question.
In C and C++, a while loop keeps running as long as its condition is true.
The key detail is: in C/C++, any non-zero value is treated as true, and 0 is treated as false.
So when you write:
while (1) {
// loop body
}
the condition 1 is always true. There’s nothing inside the parentheses that can change over time – it’s just the constant value 1. That means the loop is set up to run forever, unless you manually stop it using something like break, return, or exiting the program.
In your example:
while (1) {
cin >> number;
if (number <= 0) {
break; // this is what actually stops the loop
} else {
total = total + number;
}
}
What’s happening is:
while (1)creates an infinite loop.Inside the loop, you read a number.
If the number is
0or negative, you hitbreak, and that’s what exits the loop.Otherwise, you keep adding to
totaland go around again.
So the idea is:
while (1)= “keep looping until I decide to stop usingbreak.”The real stop condition is written inside the loop, not in the
whileparentheses.
In modern C++, you’ll also see people write while (true) instead of while (1). They mean the same thing in this context, it’s just a bit more readable.
If you have further questions, I'm here to help.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer