>> DAVID J. MALAN: Let's now implement a function that doesn't just have a side
effect, but instead returns a return value.
Specifically, let's implement a function called get positive int whose
purpose in life is to do exactly that.
Specifically, I'd like to use this function as follows--
int N gets get positive int.
And then print f, thanks for the percent i as a
placeholder, comma, end.
>> Now of course, get positive int doesn't yet exist.
So let's promise to implement it by adding to the top of my file a line
like int signifying that this function will return in int--
get positive int.
And let's specify explicitly that this function will not take any input, and
so its arguments are void.
Let's now at the bottom of my file, simply so that I can keep main up top,
actually implement or define this function.
>> First we start with the same signature, so to speak--
int get positive int void.
And now let's implement get positive int as follows.
Let's declare an int, also called N but we could call it almost anything
we'd like, do the following while some condition is true, and we'll return to
that condition in a moment.
Print f, please give me a positive int, and now let's use Get int from
the CS50 library to actually get that int.
>> But in my condition, let's do this loop so long as N is less than 1.
In other words, so long as the user does not cooperate by providing me
with a positive int, let me re-prompt him or her again, and again, and again
until he or she does.
But I'm not done yet, because at the end of this function I need to
actually do something with that input.
And so I'm going to go about returning it with a line like return end
semicolon, thereby returning an actual int to main who called this function.
Now it's worth noting that even though get positive int returns in int, it's
certainly fine for it to return a positive int specifically.
There isn't a special data type for positive integer specifically, so we
simply use the built in "int."
>> Now back at line nine, notice that I'm printing out N. But the N in this line
belongs to the N that's declared in line eight.
So it turns out you can absolutely have variables identically named so
long as they exist within different scopes.
And recall that scope is defined by the curly braces that most closely
surround the variable that you've defined.
>> Now let's compile and run this program.
Make functions 1, dot slash functions 1.
Let's give it a positive int-like 50, and it says thanks for the 50.
Meanwhile, if we don't cooperate, running the program again, giving it
0, I'm prompted again, or giving it negative 1, I'm prompted again.
But if I do cooperate providing it with, say, 50, I'm thanked for the 50.