THREAD: need help understanding increments in for loops
  1. 12-22-2017, 10:34 PM
    32
    Posts
    30
    Reputation
    May 2017
    NextGenUpdate
    why does this code skip the number 2 when counting?
    public class Program
    {
    public static void main(String[] args) {
    int result = 0;
    for (int i = 0; i < 5; i++) {
    if (i == 3) {
    result += 10;
    } else {
    result += i;
    }
    System.out.println(result);
    }
    }
    }
  2. 12-29-2017, 09:28 AM
    Sloth's Avatar
    Sloth
    Banned
    Sloth's Avatar
    Sloth
    Banned
    1,494
    Posts
    42,928
    Reputation
    Feb 2010
    NextGenUpdate
    Originally Posted by mudville209 View Post
    why does this code skip the number 2 when counting?
    public class Program
    {
    public static void main(String[] args) {
    int result = 0;
    for (int i = 0; i < 5; i++) {
    if (i == 3) {
    result += 10;
    } else {
    result += i;
    }
    System.out.println(result);
    }
    }
    }

    Your code doesn't skip 2 at all take a look at this I compiled it online and just printed out i and the result through each iteration Smile
    You must login or register to view this content.