What will be the output of the following program segment:

int a = 3;

void demo(int x, int y, int &z)

{ a += x+y;

z = a+y;

y += x;

cout<<x<<'*'<<y<<'*'<<z<<endl;

}

void main()

{ int a = 2, b = 5;

demo(::a,a,b);

demo(::a,a,b);

}

The output is: 3*5*10

8*10*20

I understood the output of the first line but couldn't figure out how the output of the second line came.It would be really very helpful if someone could explain me the output.

int a = 3;

void demo(int x, int y, int &z)

{ a += x+y;

z = a+y;

y += x;

cout<<x<<'*'<<y<<'*'<<z<<endl;

}

void main()

{ int a = 2, b = 5;

demo(::a,a,b);

demo(::a,a,b);

}

The output is: 3*5*10

8*10*20

I understood the output of the first line but couldn't figure out how the output of the second line came.It would be really very helpful if someone could explain me the output.

OK... before the first call to demo,

::a is 3

a is 2

b is 5

so on input to demo, x =3, y = 2, z = 3

In the demo function:

x is unchanged, so it is output as 3

::a (the global variable) is increased by the sum of x and the initial value of y, i.e. it becomes 3 + 3 + 2 = 8

y is increased by the value of x, so it is output as 5

z is set to the sum of the y and the new value of global a i.e. 8 + 2 = 10

Since z is passed by reference, on return to main, the value of b is changed to 10

So, before the second call, we have:

::a is 8

a is 2

b is 10

On input to the second call to demo, x = 8, y = 2, z = 10

x is unchanged, so is output as 8

::a is increased by 8 + 2, so is 8 + 8 + 2 = 18

z = 18 (::a) + 2 = 20

y is incremented by x, i.e by 8, so becomes 2 + 8 = 10.

::a is 3

a is 2

b is 5

so on input to demo, x =3, y = 2, z = 3

In the demo function:

x is unchanged, so it is output as 3

::a (the global variable) is increased by the sum of x and the initial value of y, i.e. it becomes 3 + 3 + 2 = 8

y is increased by the value of x, so it is output as 5

z is set to the sum of the y and the new value of global a i.e. 8 + 2 = 10

Since z is passed by reference, on return to main, the value of b is changed to 10

So, before the second call, we have:

::a is 8

a is 2

b is 10

On input to the second call to demo, x = 8, y = 2, z = 10

x is unchanged, so is output as 8

::a is increased by 8 + 2, so is 8 + 8 + 2 = 18

z = 18 (::a) + 2 = 20

y is incremented by x, i.e by 8, so becomes 2 + 8 = 10.

Last edited on

Topic archived. No new replies allowed.