w3resource

JavaScript: Iterates the integers from 1 to 100

JavaScript Conditional Statement and loops: Exercise-7 with Solution

Write a JavaScript program that iterates integers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for multiples of five print "Buzz". For numbers multiples of both three and five print "FizzBuzz".

Sample Solution:

JavaScript Code:

// Loop through numbers from 1 to 100
for (var i = 1; i <= 100; i++) {
    // Check if the number is divisible by both 3 and 5
    if (i % 3 === 0 && i % 5 === 0) {
        console.log(i + " FizzBuzz");
    }
    // Check if the number is divisible by 3
    else if (i % 3 === 0) {
        console.log(i + " Fizz");
    }
    // Check if the number is divisible by 5
    else if (i % 5 === 0) {
        console.log(i + " Buzz");
    }
    // If none of the above conditions are met, print the number
    else {
        console.log(i);
    }
} 

Sample Output:

1
2
3 Fizz
4
5 Buzz
6 Fizz
7
8
9 Fizz
10 Buzz
-----

Flowchart:

Flowchart: JavaScript:- Iterates the integers from 1 to 100

Live Demo:

See the Pen javascript-conditional-statements-and-loops-exercise-7 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program which compute, the average marks of the following students Then, this average is used to determine the corresponding grade.
Next: Write a JavaScript program to find and print the first 5 happy numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.