pacmanfordinner pacmanfordinner - 3 months ago 17
Javascript Question

FizzBuzz program(details given) in Javascript

Can someone please correct this code of mine for FizzBuzz!, there seems to be a small mistake, this code 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”/

/*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")
}




}

Answer
/*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”*/

var str="",x,y,a;
for (a=1;a<=100;a++)
{
    x = a%3 ==0;
    y = a%5 ==0;
    if(x)
    {
        str+="fizz"
    }
    if (y)
    {
        str+="buzz"
    }
    if (!(x||y))
    {
        str+=a;
    }
    str+="\n"
}
console.log(str);

Your functions return falsy values no matter what, but will print anyway. No need to make this overly complicated.

fiddle: http://jsfiddle.net/ben336/7c9KN/