Last active
December 30, 2019 21:28
-
-
Save maxxcrawford/a25652bb08f6cbfc5acf to your computer and use it in GitHub Desktop.
FizzBuzz Proof – JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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”." --> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
div { | |
width: 80px; | |
height: 20px; | |
line-height: 20px; | |
text-align: center; | |
outline: 1px solid black; | |
display: inline-block; | |
margin: 10px 10px 0 0; | |
} | |
.fizz { | |
background: red; | |
color: white; | |
outline: none; | |
} | |
.buzz { | |
background: blue; | |
color: white; | |
outline: none; | |
} | |
.fizzbuzz { | |
background: purple; | |
color: white; | |
outline: none; | |
} | |
</style> | |
</head> | |
<body> | |
<script> | |
// For Loop Counting from 1 - 100 | |
for (i = 1; i <= 100; i++) { | |
// Test for Multiple of 3 | |
if (i % 3 === 0) { | |
// Test for Multiple of 3 AND 5 | |
if (i % 5 === 0) { | |
document.write(" <div class='fizzbuzz'>fizzbuzz</div> "); | |
} else { | |
document.write(" <div class='fizz'>fizz</div> "); | |
} | |
// Test for Multiple of 5 | |
} else if (i % 5 === 0) { | |
document.write(" <div class='buzz'>buzz</div> "); | |
} else { | |
// If Neither 3 or 5 Multiple, Print Number | |
document.write("<div>" + i + "</div>"); | |
} | |
} | |
</script> | |
</body> | |
</html> |
Author
maxxcrawford
commented
May 21, 2015
a slightly different approach:
var i, three, five;
// For Loop Counting from 1 - 100
for (i = 1; i <= 100; i++) {
three = i%3 === 0;
five = i%5 === 0;
if (three && five) {
// Test for Multiple of 3 AND 5
document.write(" <div class='fizzbuzz'>fizzbuzz</div> ");
}
else if (five) {
// Test for Multiple of 5
document.write(" <div class='fizz'>fizz</div> ");
}
else if (three) {
// Test for Multiple of 3
document.write(" <div class='buzz'>buzz</div> ");
}
else {
// If Neither 3 or 5 Multiple, Print Number
document.write("<div>" + i + "</div>");
}
}
New way:
for (let number = 1; number <= 100; number++) {
let string = "";
if (number % 3 == 0) string += "Fizz";
if (number % 5 == 0) string += "Buzz";
if (string != "") console.log(number + ": " + string);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment