Skip to content

Instantly share code, notes, and snippets.

@mojenmojen
Last active December 17, 2023 21:55
Show Gist options
  • Save mojenmojen/21395af416630530c330904f7d7c5704 to your computer and use it in GitHub Desktop.
Save mojenmojen/21395af416630530c330904f7d7c5704 to your computer and use it in GitHub Desktop.
Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (a…
// make a loop that goes from 1 to 100
for ( var num = 1; num < 101; num ++ ) {
// check if the number is divisible by 3 or 5
var checkForThree = num % 3;
var checkForFive = num % 5;
// if the number is divisible by both 3 and 5, then print FizzBuzz
if ( (checkForThree == 0) && (checkForFive == 0) )
console.log( "FizzBuzz");
// if the number is divisible by 3, then print Fizz
else if (checkForThree == 0)
console.log( "Fizz");
// if the number is divisible by 5, then print Buzz
else if (checkForFive == 0)
console.log( "Buzz");
// otherwise just print the number
else
console.log( num );
}
/*
The second version of the program has a straightforward solution and a clever one.
The simple way is to add another “branch” to precisely test the given condition.
For the clever method, build up a string containing the word or words to output,
and print either this word or the number if there is no word, potentially by
making elegant use of the || operator.
*/
@lowCodeSherpa
Copy link

// Print number from 1 to 100
for ( let num = 1; num <= 100; num += 1) {

// if number is divisible by both 3 and 5 print Fizz Buzz
if(( num % 3 == 0) && ( num % 5 == 0)){
    console.log("FizzBuzz");
}

// if number is divisbile by 3
else if (num % 3 == 0) {
    console.log("Fizz");
}

//If number is divisble by 5
else if(num % 5 == 0) {
    console.log("Buzz");
}
else
console.log(num);

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment