Question

What is the output of the following code? for(int i =0; i<3; i++) { int x = 0; x = x+i; Sy System.out.println(x);
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here, we have given for loop which intially takes value of i = 0 then it checks condition i<3. As the condition is true (0 < 3) , so loop executes the statement in it. The first statement takes x = 0 then second statement will add up the value of x to i and then final value of x becomes 0. Now i will increase by 1 and will become 1 as 0 + 1 = 1. Now condition will be checked as earlier for i<3 which gives 1<3. Since the condition is true so the loop executes again which provides x = 0 and then adding x and i which will make x = 0 + 1 = 1. Now i will again increase by 1 and will become 1 + 1 = 2. After this condition will be checked as i < 3 that is 2<3. As the condition is true, the loop executes and will give x = 0 and adding x and i to give x = 2 + 0=2. Now i will increase again and become 3(2 + 1 = 3). When condition will be checked that is 3 < 3, it becomes false. So loop will not be executed further and the control will come out of the loop to next statement after the loop which prints the value of x = 2 which is the stored value of x variable during the last time of execution of loop. So in this way the for loop executes in 3 steps: Declaration of variable, Condition Check and Increment or Decrement of variable.

Add a comment
Know the answer?
Add Answer to:
What is the output of the following code? for(int i =0; i<3; i++) { int x...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT