Java: Create method to print all multiples of 3 between 1 and n?

So the question is asking to create a method that will take an integer x as a parameter and print out all integers from 0->x that are multiples of three.

I can print out the number of times three divides x like so:

 public int Threes(int x){ int i = 0; for(int counter = 1; counter <= x; counter++){ if (counter % 3 ==0){ i ++; } } return i; 

but I'm not sure how to print out each multiple of 3!?

2

4 Answers

for(int counter = 1; counter <= x; counter++){ if (counter % 3 ==0){ System.out.println(counter); } } 

An even quicker approach would be to increment by 3

public void Threes(int x) { for (int counter = 3; counter <= x; counter = counter + 3) { System.out.println(counter); } } 

This loop will jump right to the multiples of 3, instead of counting every single number and having to do a modulo check for each iteration. Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. If the input happens to be less than 3, then nothing will be printed. Also, the function should be void since you're printing instead of returning anything.

(Your title says 1 to n, but your question says 0 to n, so if you actually need from 0 to n, then change the declaration of counter to int counter = 0;)

Jason Aller wow that was so simple and elegant. This one builds on it by counting down from 300 to 3, by 3's.

public class byThrees { public static void main(String[] args) { for (int t = 100; t >= 0; t--) { System.out.println(t*3); 

Best practice using the For-loop in Java.

public class MultiplesOfThree { public static void main(String []args){ for (int m = 1; m<=12; m++){ System.out.println(m*3); } } } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like