FizzBuzz Program in Java - Interview Question

FizzBuzz: A most famous interview question
Hmm. Let us see the most famous interview question i.e. FizzBuzz. In this post i'll discuss what is FizzBuzz question and how to outsmart this.

What is FizzBuzz?

In this question, you will work with two numbers 3 and 5. The user gives a number as input and then we'll have to get the list of all the numbers starting from 1 till the given number. Now, all we need to do is to find the numbers that are multiples of 3 and 5 and print special words called Fizz and Buzz instead of those multiples respectively. If a number is multiple of both 3 as well as 5 (say 15) FizzBuzz should be printed and if a number is neither a multiple of 3 nor 5 then the number itself is printed. Now let us see how this works.


import java.util.*;
class FizzBuzz
{
    public static void main(String args[])
    {
    Scanner s=new Scanner(System.in);
   
    System.out.println("Enter the number");
   
    int n=s.nextInt();
   
        for(int i=1;i<=n;i++)
        {
            if(i%5==0)
            System.out.println("Buzz");
            else if(i%3==0)
            System.out.println("Fizz");
            else if((i%3==0)&&(i%5==0))
            System.out.println("FizzBuzz");
            else System.out.println(i);
        }
    }
}

Output


Enter the number
15
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Buzz

Explanation

To know the multiples of a number we'll have to find out the remainder and it should be 0. The same logic is used there.

if(i%5==0) means if a number is multiple of 5 then print Buzz.
if(i%3==0) means if a number is multiple of 3 then print Fizz.
if((i%3==0)&&(i%5==0)) means if a number is multiple of 3 as well as 5, then print FizzBuzz.

That's it, this is a way in which we can outsmart this most famous interview question, the FizzBuzz

No comments: