Function Program

How do I work on such program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int f1(int x, const int& y, int& z);

int main()
{
int a=10, b=20, c=30, y;
y = f1(a, b, c); //Meaning of this? 
cout << "A: " << a << endl;
cout << "B: " << b << endl;
cout << "C: " << c << endl;
cout << "Y: " << y << endl;
return 0;
}

int f1(int x, const int& y, int& z)
{
x += y;
z += x;
return (x+y+z);
}
I believe that means that a goes into x form f1 b into y and c into z
Well first of all, you need to include the iostream header and need to use the namespace std for that to work, hopefully you already know that..... on line five you create variables named a, b, and c and give them values, you also create y but don't give it a value. On line six you give y the return value of the function named f1, so what ever f1 returns is what y equals. You pass three parameters a, b, and c which hold the values 10, 20, and 30. So the function does some calculating and then returns a value, what ever is returned is set to the value of y. Hopefully you understood what I said, if not reply with what you didn't understand.
Last edited on
Tks ppl. I got the calculation out now.
y = f1(a, b, c); is setting y to the output of the function f1

Function f1 is defined from line 14 to line 19:
1
2
3
4
5
6
int f1(int x, const int& y, int& z)
{
   x += y;
   z += x;
   return (x+y+z);
}


So the meaning of y = f1(a, b, c); is y = (x+y)+y+(z+(x+y)). Or y =(10+20)+20+(30+10+20). So y= 110

Maybe this will help:
Think of line 5: y = f1(a, b, c); as y = f1(10, 20, 30);.

What happens next is f1 is called with the three values 10, 20, and 30.

Inside f1 those values get new names: x, y, and z. So here x=10, y=20 and z=30. (Remember the &'s here in line 14, they will be important.)

x += y; is short hand for x = x + y here x becomes 10+20.
z += x; same sort of shorthand: z = z + x; so z becomes 30 + 30
lastly, the function returns x+y+z, AKA 30 + 20 + 60 = 110.
now we're back at line 6 setting y = 110;

BUT the person who wrote the code was tricky, and returned data two different ways. The first way was directly though a return value, but the second way was by passing 2 of the variables by reference, that's what the &'s were for. That means that the value of those two variables gets returned to main and put back into their original variable names (b and c).

That is how to look at the program.

I'll leave it up to you to figure out what the final output will be.

Hope this helps!
Topic archived. No new replies allowed.