1

For a simple Java program where I want to make the program count from 10 to 1 by incrementing of 2 or 3 or 4 how would I change this code?

public class ExampleFor {

    public static void main(String[] args) {
        // 
        for(int i = 10; i > 0; i--){
            System.out.println("i = " + i);
        }

    }
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Sempliciotto
  • 107
  • 1
  • 2
  • 6

2 Answers2

7

change the for loop to:

for (int i=10; i>0; i-=2) {
    System.out.println("i= "+i);
}

i-=2 is an abbreviation for i = i-2
It means that the new value of i will be the old value of i minus 2.
i-- is an abbreviation for i = i-1, which can be also written as i-=1

vefthym
  • 7,422
  • 6
  • 32
  • 58
3

Just use this method and give it the number to decrement with in param:

public static void count(int counter) {

  for(int i = 10; i > 0; i-=counter){
        System.out.println("i = " + i);
  }
}

For exmaple to decrement by 2 use:

count(2);

And your main will be like this:

public static void main(String[] args) {

    count(2);// to decrement by 2
    count(3);// to decrement by 3
    count(4);// to decrement by 4

}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78