A while loop is used to do a specific something while the Boolean expression is true. Take the following code:
int a = GetInt();
while( a > 0 )
{
// code
}
a > 0
is our Boolean expression. The loop will execute as long as this is true. But, if a
is not greater than 0, the Boolean expression will evaluate to false, which will stop the while
loop. It is possible for a while loop to never execute if the Boolean expression evaluates to false. But sometimes you want the loop to execute once, right? Say you want to ask someone something once, and then keep asking if they don't give the right answer. That's where do/while loops come in.
Do/while loops execute once and keep executing as long as the Boolean expression is true. Your line of thinking seems correct - you want n
to be, in the end, greater than 0, correct? But what if the Boolean expression is n > 0
? The do/while loop will keep executing as long as n
is positive - thus, it'll only stop prompting the user if the user gives a negative number!
Now, n < 0
vs. n <= 0
. We want a positive number, right? 0 is technically not a positive number nor a negative number, so it wouldn't work to count it as positive. n < 0
would allow 0 to count as a positive number, even though it shouldn't. Thus, n <= 0
works to prompt the user as long as they enter a negative number or 0.
If it helps you, here are CS50's definition of these loops:
while: Use when you want a loop to repeat an unknown number of times, and possibly not at all.
do-while: Use when you want a loop to repeat an unknown number of times, but at least once.
Let's look at while(n <= 0)
and while(n < 1)
. These are essentially the same, because both check for 0 and negative numbers. n <= 0
simply specifies to check if n is less than or equal to 0, while n < 1
checks if n is less than 1.
However, if it was n >= 0
and n > 1
, these would be different. In n >= 0
, it is checking if n is greater than or equal to 0. This includes 0, 1, 2, 3, and so on. In n > 1
, it checks if n is greater than 1. This includes 2, 3, 4, and so on, but not 0 or 1. The difference is that n >= 0
includes 0 and 1 while n > 1
doesn't.
If you still have issues/questions, comment below.