Detailed Print – CSKC
Sign In

Search

siteicon
Solved Problem!#CPP#2346 Back

Problem Statement - Output writing – loop with unary operators in cout chain

Solve the following program to show its output. Assume that required header files are included

int main() 
{
  int a,b;
  a=(b=10);
  for(int i=10;i<30;i+=10)
  {
    cout<<a++ + i<<" "<<(b=++b -i)<<endl ;
  } 
  return 0;
}

		 

Click to open popup

Run Output

20 1
31 -18

Solution

Notes

int a,b; //Two variables have been declared here
a=(b=10); //First value of 10 is assigned to b on LHS and then whole LHS is assigned to a

for(int i=10;i<30;i+=10)
This loop begins with 10 and goes till less than 30 with update instruction increasing i by 10 in each iteration. With given conditions loop is expected to run 2 times only. Once with i=10 and next time with i=20.

cout<<a++ + i<<” “<<(b=++b -i)<<endl ;
Let us evaluate a++ +i in first iteration. a++ will be 10 and i will be 10 so 20 will be printed.
Now (b=++b-i) would be ++b would be 11 and -i which is 10 would make it 1. So b will be 1 and will get printed.

In second iteration let us do for a++ + i again. Since a would become 11 due to previous a++, so this would evaluate to 11+20 = 31.
The second expression (b=++b-i) would be : ++b would become 2 and -i or 20 will make it -18, so -18 would be printed.

Common Errors

  • The change is value of b in the second iteration is often overlooked by the students.