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 – double increment in loop
Write the output of the following code. Assume that required header files are included.
int main()
{
for(int i=10;i<=50;i+=10)
cout<<i++/2<<" ";
return 0;
}
Solution
TC++ #2031
Run Output
5 10 16 21
Notes
for(int i=10;i<=50;i+=10) cout<<i++/2<<” “;
This is a double increment loop. One increment is there in the for loop 3rd instruction and another inside the for loop. Watch –
First iteration : i will be 10, so i/2 will be 5;
Second iteration: i will become 10+1 and i+10 will become 21. now i/2 will be 10 as only integer portion of 21/2 will be retained.
Third iteration : i will be 21+2 because of i++ and i+10 will be 32 , so i/2 will be 16;
Forth iteration:i will be 32+1 which is 33, i+10 will be 43, so i/2 will be 21 because of integer division.
Fifth iteration attempt: i will be 43+1 which is 44 and i+10 would be 54, which is larger than 50 so loop will terminate.
So the output would be 5 10 16 21
Such programs need to be dry run by the user by putting values of loop variable one by one and then calculating the final value with patience.
Common Errors
It should be noted that third instruction which is i+=10 (increment by 10) is always tried as the last instruction of the loop and then only next condition of loop is tried.