get every other element out of a for loop or array

hi somewhat novice programmer. I am trying to get every other element from an array or loop actually.

for(int i =0;i<5;i++){ println(i); } //it prints 0,1,2,3,4

is there a function to get it to print 0,2,4 and then a way to invert it to get 1,3...so I can draw a line through a 2d array. thanks.

Tagged:

Answers

  • @jjdelorimier== that 's easy

            for(int i =0;i<5;i++)
            { println("i1===" + i);
            }
    
            for(int i =0;i<5;i=i+2)
            { println("i2===" + i);
            }//it prints 0,2,4
    
            for(int i =1;i<5;i=i+2)
            { println("i3===" + i);
            }//it prints 1,3
    
  • for (int i = 0; i < 5; i += 2) {
    

    Nicer with some spaces, IMHO...
    i++ is, somehow, a shortcut to i += 1, so you can make increments of any size.

  • Thanks guys appreciate it!

Sign In or Register to comment.