Saturday 30 January 2016

Write a program in java to check the number is FizzBuzz number or not.

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.

Program:
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.

1 comment: