Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FizzBuzz program (details given) in Javascript [closed]

Can someone please correct this code of mine for FizzBuzz? There seems to be a small mistake. This code below prints all the numbers instead of printing only numbers that are not divisible by 3 or 5.

Write a program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".

function isDivisible(numa, num) {
  if (numa % num == 0) {
    return true;
  } else {
    return false;
  }
};

function by3(num) {
  if (isDivisible(num, 3)) {
    console.log("Fizz");
  } else {
    return false;
  }
};

function by5(num) {
  if (isDivisible(num, 5)) {
    console.log("Buzz");
  } else {
    return false;
  }
};

for (var a=1; a<=100; a++) {
  if (by3(a)) {
    by3(a);
    if (by5(a)) {
      by5(a);
      console.log("\n");
    } else {
      console.log("\n");
    }
  } else if (by5(a)) {
    by5(a);
    console.log("\n");
  } else {
    console.log(a+"\n")
  }
}
like image 872
pacmanfordinner Avatar asked May 18 '13 04:05

pacmanfordinner


People also ask

What is FizzBuzz problem in Javascript?

What is FizzBuzz? Firstly, let's get this out of the way, FizzBuzz is a task where the programmer is asked to print numbers from 1 to 100, but here's the catch, multiple of three should print “Fizz” and similarly print “Buzz” for multiples of 5 and lastly print “FizzBuzz” for multiples of three and five.

How do I fix my FizzBuzz?

The most obvious way to solve FizzBuzz is to loop through a set of integers. In this loop, we use conditional statements to check whether each integer is divisible by three and/or five. The code above takes this approach. First, we store integers one-to–50 in the vector fbnums .

What is FizzBuzz program?

Fizz buzz is a group word game for children to teach them about division. Players take turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number divisible by five with the word "buzz".


1 Answers

for (let i = 1; i <= 100; i++) {
    let out = '';
    if (i % 3 === 0) out += 'Fizz';
    if (i % 5 === 0) out += 'Buzz';
    console.log(out || i);
}
like image 198
Trevor Dixon Avatar answered Sep 28 '22 02:09

Trevor Dixon