0
import java.util.*;
public class demo{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        for(int i=0;i<5;i++){
            System.out.println(i);
            i=i+2;
        }
    }
}

I tried this question, according to me the output will be

0
2
4

But, the output coming is

0
3

please explain

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 7
    You'd be much better of [learning how to use a debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). That will allow you to view everything that is happening when you run the program, set your own stop-points etc pp. The short answer to your question is however that you seem to forgot the `i++` from the loop itself that happens after every iteration. – OH GOD SPIDERS Apr 18 '23 at 14:15
  • 5
    You would be correct **if** the code were `for(int i=0;i<5;){` examine how that differs from what you actually have. – Elliott Frisch Apr 18 '23 at 14:29
  • 1
    If you explain, step-by-step, why you think the output will be `0 2 4`, it will be easier for someone to see exactly where the misconception is - and then correct it. – andrewJames Apr 18 '23 at 15:41
  • Thnku so much! Now I understood. Actually I have updated the value of i two times.That's why I am not getting the desired output. – MUKUL NAGPAL Apr 19 '23 at 14:23

1 Answers1

4

Numbering the lines of code:

1        for(int i=0;i<5;i++){
2            System.out.println(i);
3            i=i+2;

1: sets i to 0, tests i<5 - passes so loops

2: prints i, which is 0

3: increases i by 2 to 2

1: increases i by 1 (;i++) to 3, tests i<5 - passes so loops

2: prints i, which is now 3

3: increases i by 2 to 5

1: increases i by 1 (;i++) to 6, tests i<5 - fails so exits the loop

John Williams
  • 4,252
  • 2
  • 9
  • 18