The FizzBuzz Algorithm is very simple to learn.
Primarily there are following steps in the algorithm:
1. Pass an integer array as input
2. Iterate the given array
3. While iterating check:
- if the current value of i is divisible by 3, if yes then it is a Fizz value
- if the current value of i is divisible by 5, if yes then it is a Buzz value
- if the current value of i is divisible by both 3 and 5, if yes then it is a FizzBuzz
Below is the Java example of FizzBuzz where an integer type array of value from 1 to 100 is considered as input values.
package com.learning.algorithm.fizzBuzz;
public class FizzBuzz {
public static void main(String[] args) {
int intArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 };
findFizzBuzz(intArray);
}
private static void findFizzBuzz(int[] intArray) {
// iterate the array
for (int i : intArray) {
// check if the value of i divisible by 3 then it is a Fizz
if (i % 3 == 0) {
System.out.println(i + " is a Fizz");
}
// check if the value of i divisible by 5 then it is a Buzz
else if (i % 5 == 0) {
System.out.println(i + " is a Buzz");
}
// check if the value of i divisible by 3 and 5 then it is a FizzBuzz
if (i % 3 == 0 && i % 5 == 0) {
System.out.println(i + " is a FizzBuzz");
}
}
}
}
The code produces the following output
3 is a Fizz
5 is a Buzz
6 is a Fizz
9 is a Fizz
10 is a Buzz
12 is a Fizz
15 is a Fizz
15 is a FizzBuzz
18 is a Fizz
20 is a Buzz
21 is a Fizz
24 is a Fizz
25 is a Buzz
27 is a Fizz
30 is a Fizz
30 is a FizzBuzz
33 is a Fizz
35 is a Buzz
36 is a Fizz
39 is a Fizz
40 is a Buzz
42 is a Fizz
45 is a Fizz
45 is a FizzBuzz
48 is a Fizz
50 is a Buzz
51 is a Fizz
54 is a Fizz
55 is a Buzz
57 is a Fizz
60 is a Fizz
60 is a FizzBuzz
63 is a Fizz
65 is a Buzz
66 is a Fizz
69 is a Fizz
70 is a Buzz
72 is a Fizz
75 is a Fizz
75 is a FizzBuzz
78 is a Fizz
80 is a Buzz
81 is a Fizz
84 is a Fizz
85 is a Buzz
87 is a Fizz
90 is a Fizz
90 is a FizzBuzz
93 is a Fizz
95 is a Buzz
96 is a Fizz
99 is a Fizz
100 is a Buzz