Skip to content

Mastering Loops and Iteration: Understanding the Differences between i vs i++

    In programming, i and i++ are both related to loops and iteration.

    i refers to the value of a loop variable i.

    It is used to keep track of the number of iterations in a loop.

    For example, in a for loop:

    for (int i = 0; i < 10; i++) {
    // loop body
    }

    i starts with a value of 0 and increments by 1 after each iteration of the loop.

    The loop continues until i is no longer less than 10.

    i++ is a shorthand notation for incrementing the value of i by 1.

    It is equivalent to writing i = i + 1.

    It is often used in the increment portion of a for loop, as shown above.

    It is important to note that there is a difference between using i and i++ in different parts of the loop.

    Using i refers to the current value of i, while using i++ increments the value of i by 1 after it has been used in the loop body.

    For example, consider the following code:

    int i = 0;
    while (i < 10) {
    System.out.println(i++);
    }

    In this code, i starts with a value of 0 and is incremented by 1 after it is used in the println statement.

    This means that the output will be the numbers from 0 to 9, inclusive.

    If we had used i instead of i++, the output would have been the numbers from 1 to 10, inclusive.