Sempliciotto
Sempliciotto

Reputation: 107

How to count from 10 to 1 in java

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);
        }

    }
}

Upvotes: 1

Views: 60031

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

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

}

Upvotes: 3

vefthym
vefthym

Reputation: 7462

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

Upvotes: 7

Related Questions