Hi fellow students, I am trying to solve a question I found on a book which is from a range o numbers, print those divisible by 3, them print those only divisible by 5, them print those divisible by both 3 and 5. I have the following code by its not completely right…
let numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for(let i = 0; i < numbers.length; i++){
if(numbers[i] % 3 === 0){
console.log(numbers[i] + ' is div by 3');
} else if(numbers[i] % 5 === 0){
console.log(numbers[i] + ' is div by 3')
} else if(numbers[i] % 3 === 0 && numbers[i] % 5 === 0){
console.log(numbers[i] + ' are both div by 3 and 5' );
} else {
console.log("no fizz or buzz");
}
}
Hi
sorry I have corrected that mistake already. here is my code:
let numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for(let i = 0; i < numbers.length; i++){
if(numbers[i] % 3 === 0){
console.log(numbers[i] + ' is div by 3');
} else if(numbers[i] % 5 === 0){
console.log(numbers[i] + ' is div by 5');
} else if(numbers[i] % 3 === 0 && numbers[i] % 5 === 0){
console.log(numbers[i] + ' are both div by 3 and 5' );
} else {
console.log(numbers[i] + " no fizz or buzz");
}
}
but my second else if is not working, which is when a number is both div by 3 and by 5 at same time
Change the order of statements. Check for divisibility by 3 and 5 first, then individual tests by 3 and 5.
let numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for(let i = 0; i < numbers.length; i++){
if(numbers[i] % 3 === 0 && numbers[i] % 5 === 0){
console.log(numbers[i] + ' is div by both 3 and 5');
} else if(numbers[i] % 5 === 0){
console.log(numbers[i] + ' is div by 5');
} else if(numbers[i] % 3 === 0){
console.log(numbers[i] + ' is div by 3' );
} else {
console.log(numbers[i] + " no fizz or buzz");
}
}
else if only evaluates when previous if/else ifs are false. Given a number that is divisible by both 3 and 5 is also divisible by either, the order of your conditions/clauses is very important
@tapputi mentioned changing the order, but does not explain why
let numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for( let i = 0; i < numbers.length; i++){
if(numbers[i] % 3 === 0 && numbers[i] % 5 === 0){
console.log(numbers[i] + ' are both div by 3 and 5')
} else if (numbers[i] % 3 === 0){
console.log(numbers[i] + ' is divisible by 3')
} else if (numbers[i] % 5 === 0){
console.log(numbers[i] + ' is divisible by 5')
} else {
console.log('no fizz and buzz')
}
}