1

Why is output 12?

Comments
  • 4
    i++ and ++i both increment the i variable with one and to understand what is happening I will explain both.

    i=9
    i++ < 10 // true, increases i with one after the condition is performed.

    i=9
    ++i < 10 // false, i is incremented and then will do the check.

    If you want to see what is happening in your example remove the last semi colon. And you will see all values of i.
    for( i=5; i++ < 10; i++) ;
  • 9
    Did you intentionally leave the printing outside the for loop?
    Do you intentionally use a white theme?
  • 1
    It's just 2 lines and so many things seem odd here.
  • 1
    @jespersh kinda
  • 1
    @irene i = 0 gives all even value b/w 0 to 10 and odd values when i = 1
  • 1
    @electrineer yea its bright here so dark theme can wait, and yes
  • 1
    @irene idk i'm just not getting all this post-pre increment and decrement thing it's so confusing for me right now, can you suggest some good tutorials about them
  • 2
    @kartik1999123 since I gather you are really new with programming you might not know some of the words @irene used.

    A for loop consists of 4 parts, I will call it a, b, c and d in the following example and then describe what each part does below.

    for( a; b; c) {
    d
    }

    *a: the initializer, can set variables to a base value or can, depending on the language even be empty. (ex: `int i = 0`)
    *b: the condition, while the condition is true execute the body (*d) and after that has executed do statement *c.
    *c: an expression generally used to modify the loop variable (normally defined at *a). Although it can modify other variables as well.

    Now to your issue:
    In your first code you assign 5 to i. This is correct
    In your condition you increment i. In general this is not what you want (unless you know what you are doing)
    In the *c expression you increment i. This is perfectly fine.
    Then you close the line with a semicolon. This creates the for loop without body (*d)
    (TO BE CONTINUED)
  • 2
    In the end you will want to have something like:

    int a;
    for( a=0; a<10; a++) {
    System.out.println(a) ;
    }
  • 1
    @Codex404 please don’t encourage weird meaningless implementations, you time is more valuable to solve real problem. Such as change the ide to dark theme.
  • 0
    @sunfishcc where did I encourage weird implementations
  • 0
    @Codex404 he clearly intentionally added unnecessary incremental in the for loop. Unless there’s a good reason to do, you don’t have to answer it seriously 😐
Add Comment