>> SPEAKER: Let's implement a program that prompts the user for an integer
but continues prompting them for another integer until
that integer is positive.
Well, let's write this, include cs50.h, include standard io dot h, int
main[void].
Now let's actually begin to prompt the user for this integer while keeping in
mind that we want to reprompt them until that
number is actually positive.
>> So I'll want some kind of looping construct, but a loop that executes at
least once.
And recall the do-while loop allows us to do exactly that.
Let's code this up.
>> Let's first declare an int-- we'll call it n-- in which to store the
user's integer.
Let's now do the following.
Printf, please give me a positive int.
Let's now get that int using the CS50 library's GetInt
function, n gets GetInt.
And now we're done doing something, but we're going to want to do this
while n is--
what?--
less than 1, if we indeed want a positive integer.
>> Let's go ahead now and print out.
If all is well, thanks for the positive int,
semicolon, save the file.
Let's now compile and run.
>> Make positive dot slash positive.
And now I'm being prompted for a positive int.
Let me cooperate with 1.
Thanks for the positive int.
>> Let's now rerun this program and not cooperate.
Please give me a positive int.
How about negative 1?
Interesting.
The program is already reprompted me for an int.
>> Let's be slightly more difficult with 0.
Still not a positive int, so let's cooperate and this time
provide, again, 1.
Thanks for the positive int.
>> Now it's important to note that I declared my variable n on line 6,
outside of the do-while loop.
Had I instead declared n inside of my do-while loop, specifically on, say,
line 10, where I also get the int from the user, that int n would have only
existed within the confines of the curly braces that are currently on
line 8 and on line 11.
>> In other words, n would be scoped to the inside of that do-while loop.
But the problem is that we also want to use n in line 12
inside of the condition.
So even though it doesn't look so pretty, it's very much deliberate that
n is declared outside this do-while loop.