We need a local variable to accumulate our answer. output is that local variable within square().
|
So, the variable that is returned is what the call function becomes? As in,
output
, which would be equal to 4 if the call function was
square(2)
, is what
square(2)
becomes once returned?
I don't understand your question. square() needs an argument (the number you want to square). What "extra input" are you referring to?
|
What I meant was whether or not extra lines of code, other than the call function, would be required to return a value. Having played around with the code a little bit, I now realise that you do not need an input value by the user to return a value to the call function at run time.
This is the code I have now. This should give you a clearer view of what I was trying to achieve.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include "std_lib_facilities.h"
int square(int x)
{
int output = 0;
for (int i = 0; i < x; i++)
{
output = output + x;
}
return output;
}
int main()
{
cout << square(/*0, 1, 2, 3...*/) << endl;
return 0;
}
|
That
for
loop is very clever. At first I didn't understand how it was squaring the call function value, but I think I have it now.
Summary
int x
, which is the equivalent to the value the call function
square()
receives, is implemented into the conditional branch of the
for
loop, thereby becoming the determining factor as to how many times the loop iterates. If the value is two, the loop iterates twice, if it's four, four times, etc.
The actual variable, in this case
output
, within the loop statement receives an accumulative value depending on how many iterations of the loop there are. This is because the value of
output
increases with each iteration, due to
x
being added to it, and continues to increase until
i
is no longer less than
x
.
Once
i
is no longer less than
x
, the loop ends and
output
has its final value, which is then returned to the call function
square()
. This is the value we see when we output the call function.
Please let me know if my summation of the function process is in any way inaccurate. I'm really trying to nail this one.