Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
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;
}
TC++ #2346
Solution
Run Output
20 1
31 -18
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.