0

I'm trying to write a code that finds the multiples of 3 and 5 in an array of numbers 1 to 100, the code I have generates the numbers I want but it gives me the multiples of 3, then gives me the multiples of 5 (Example: 3 6 9 12 15,5 10 15) I want them all together (Example 3 5 6 9 10 12 15).

here is the code I have so far

for(int i = 0 ; i < 100; i=i+3){
      if(i%3 == 0)
       System.out.println(i);
       }
    for (int i=1; i < 100; i++) {
            if (i%5==0) System.out.println(i);}

I also tried

if(i%3 == 0 && i%5==0)

but that only gave me the numbers divisible by both

an explanation after would be helpful thank you

pushkin
  • 9,575
  • 15
  • 51
  • 95
Fiendnyx
  • 45
  • 1
  • 1
  • 3

5 Answers5

4

You want numbers that are divisible by 3 OR divisible by 5. Therefore you should use || (OR) instead of && (AND):

for (int i = 0 ; i < 100; i++) {
    if(i%3 == 0 || i%5==0) {
        System.out.println(i);
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

You can try the following to get 3,5,6,9,10,12,15..

for(int i = 0 ; i < 100; i++) { //Loop from 0 to 100
      if(i % 3 == 0 || i % 5 == 0 ) //check the number is divisible by 3 or 5
       System.out.println(i); //print the number if it is divisible by 3 or 5
}
Lav Shah
  • 11
  • 2
0
 for(int i=1;i<=100;i++){
    if(i%3==0||i%5==0)
        System.out.println(i)
    }

The above code give you the number which can be divided either by 3 or 5

buqing
  • 925
  • 8
  • 25
0
public class Multiple {

    public static void main(String[] args) {
        int i;
        for (i = 0; i <= 100; i++) {
            if (i % 3 == 0 || i % 5 == 0) {
                System.out.println(i);
            }
        }
    }

}
bedrin
  • 4,458
  • 32
  • 53
Chetan J Rao
  • 905
  • 9
  • 14
0

Didn't put too much time into this but what about just using a variable so it doesn't repeat:

public class main {
    public static void main(String[] args) {
        boolean printed = false;
        for(int i = 0 ; i < 100; i++){
            printed = false;
              if(i%3 == 0 && printed == false){
               System.out.println(i);
               printed = true;
              }
              if (i%5==0 && printed == false) System.out.println(i);}   
     }
}