0

What is the output and why??

int x = 0; int &y = x; y = 5; while(x <= 5) { cout << y++; x++; } cout << x;

31st Aug 2020, 11:25 AM
Gujjula Pradeep Reddy
Gujjula Pradeep Reddy - avatar
5 Respostas
+ 4
Variable <y> is an int reference, points to variable <x>. A reference acts like an alias for something it refers to, so in this case <y> is like an alias for <x>. When <x> is modified, the changes also reflects in <y>, vice versa. * About reference type: https://techdifferences.com/difference-between-pointer-and-reference-2.html So when you modify <y> y = 5; <x> value also changes to become 5. Next, a while-loop is setup to go while <x> is less than or equal to 5. The condition satisfies, so the loop begins ... Inside the loop body <y> value is printed then incrented, and <x> value is incremented. cout << y++; Here value of <y> is printed (5) and then incremented to become 6. x++; Here value of <x> (6) is incremented to become 7. NOTE: Remember that <y> is a reference to <x>, so when <y> is incremented, <x> also gets incremented. Also when <x> is incremented, <y> also gets incremented.
31st Aug 2020, 1:11 PM
Ipang
+ 4
First you have to understood the concepts of reference variable how this is working . For example i write Int x=5; Int x=&y ; If i will increment the value of 5 then y will also increment . Here y is reference of x . If u will change x then y will automatically change if i will add 2 in x means x=x+2, 5+2 so x will be 7 then y also will be 7. In this program What is the output and why?? int x = 0; int &y = x; y = 5; while(x <= 5) { cout << y++; x++; } cout << x; here y is reference of x here y is 5 means x is automatically 5 after that in while statement while(5<=5) which is true after that cout<<y ; here value of y will be print which is 5 after that post increment will increase then value of y so after printing 5 it will increase by 1 so i will be 6 . If y is 6 then x will be also 6 beocz of reference. After that we incrementing value of x++ here x will increase but what was the value of x it was 6 so x++ means x will be 7.If x is 7 so loop will check condition while(7<=5)
31st Aug 2020, 1:14 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 3
Here condition will be false so it will throughout from loop so next cout will print value of x cout<<x ; and x was 7 so complete Output is 57. ...........Thankyou...........
31st Aug 2020, 1:16 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Do you want the output or an explanation of the output? if you want the output then go to Code Playground to check it.
31st Aug 2020, 11:36 AM
Ipang
0
I want to know why??
31st Aug 2020, 11:40 AM
Gujjula Pradeep Reddy
Gujjula Pradeep Reddy - avatar