-1

I am teaching a simple comparisons on programming, but I have found something odd when I am trying to list all the natural numbers below 10 that are multiples of 3 or 5, when I add the following conditions the number 0 is added, even when specifically is conditional to add numbers if they are different from 0, I have already made invalidate caches and restart to Android Studio. Am I missing something here? Below is the code

 fun multiplesOf() {
        val arrayOfSelected: ArrayList<Int> = arrayListOf()

        for (i in 0..10) {
            if (i != 0 && i % 3 == 0 || i % 5 == 0) {
                arrayOfSelected.add(i)
            }
        }
        Log.i("TAG", "multiplesOf: $arrayOfSelected")
    }
1
  • you need to realize that 0 % any number == 0. Try changing up your condition a bit, maybe along the lines of if (i != 0 && ( i % 3 == 0 || i % 5 == 0 ) ) { to make it "not zero and 'divisible by 3 or 5'" instead of the current "not zero and divisible by 3 or 5" because the 'or 5' will short-circuit you every time.
    – Shark
    Oct 19, 2022 at 9:08

2 Answers 2

3

The only bug is in your boolean expression:

Given i=0

i != 0 && i % 3 == 0 // this is false
||
i % 5 == 0 // this is true

This is basic Bool's arithmetic: false or true => true and hence will execute your if's block

Adding parenthesis might help you get the desired outcome:

if ( i != 0 && (i % 3 == 0 || i%5 ==0) ) {...}
1
  • this. exactly this.
    – Shark
    Oct 19, 2022 at 9:10
1

This will evaluate to 0

i % 5 == 0 

executing your

arrayOfSelected.add(i) 

which will add 0

I'd suggest add another condition to continue the loop when i == 0

if (i == 0) {
   continue
} else {
  
    if (i % 3 == 0 || i % 5 == 0) {
          arrayOfSelected.add(i)
    }
}

prints:

multiplesOf: [3, 5, 6, 9, 10]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.