# Cisco sytem interview question

11 views

Can someone please expain the output of these two programs.

#include <iostream>

using namespace std;

int main() {

int x = 1, y = 1;

y = ++ x + ++ y;

cout << "x = " << x << endl;

cout << "y = " << y << endl;

return 0;

}

Output:

x = 2

y = 4

Can anyone explain the Output of this code by dry run.

...................................................................................

#include <iostream>

using namespace std;

int main() {

int x = 1, y = 1;

x = x ++ + ++y;

cout << "x = " << x << endl;

cout << " y = " << y << endl;

return 0;

}

Output:

x = 3

y = 2

For further information, this question is taken from here

careercup.com

x = x++ + ++y; y = ++x + ++y; what are the values of x,y after these are executed ?

1] #include <iostream>
2] using namespace std;

3] int main() {
4]  int x = 1, y = 1;
5]  y = ++ x + ++ y;
6]  cout << "x = " << x << endl;
7]  cout << "y = " << y << endl;
8]  return 0;
9] }


5th line gets executed by first computing result of right hand side expression into register(or directly into LHS var depending on architecture) and then that value gets stored into whatever variable is there on left hand side.

So, While evaluating RHS expression value of x is updated to (x+1) and y gets updated to (y+1) and the effective value of x and y that is used in evaluating the expression is 2 and 2 respectively. So we get value of expression (2 + 2) which is 4. This value gets stored in variable y.

So final value of x is 2 and that of y is 4.

Now coming to the second program.

Some facts:  if $x$ contains value $0$ initially then exprssion y = x++; will result in y being 0 and x being 1;

Because postfix ++ operator first increments x then returns the nonupdated(unincremented) value of x(i.e 0 in this case).

Similarly prefix ++ operator will increment x and returns the incremented value. So y = ++x; will result in y and x both being 1.

Now coming to your program we have

x = x++ + ++y;

Which is logically equivalent to(in this instance)

x = 1 + 2          $(\because$ x++ will return the unincremented value of x i.e 1 and ++y will return incremented value of y i.e 2$)$

now at the time of evaluating the expression value of x will be updated to x+1 because of postfix increment operator. (This assignment to x will soon be overwritten. :) )

After that value of evaluated expression which is 3 will be assigned to x.

So final value of x is 3 and that of y is 2.

199 points
edited
0
Please solve the second program because that’s where the problem is.
0
Ok will be editing the answer soon.