Wednesday, 19 August 2015

Prints the numbers from 1 to 50 but for multiple of 3,5 print Fizz,Buzz,FizzBuzz.

package com.JavaInterview.Programs;
import java.util.*;

/* Write a Java program that prints the numbers from 1 to n. 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"
 * */

public class FizzBuzz {

 public void printFizzBuzz(int n)
 {
  for(int i=1;i<n;i++)
  {
   if(i%(3*5)==0)
   {System.out.println("FizzBuzz");}
   else if(i%3==0)
   {System.out.println("Fizz");}
   else if(i%5==0)
   {System.out.println("Buzz");}
   else
   {System.out.print(i+" ,");}
  }
 }

 public static void main(String args[])
 {
  Scanner input=new Scanner(System.in);
  System.out.println("Please enter the length of series");
  int num=input.nextInt();
 
  FizzBuzz fb=new FizzBuzz();
  fb.printFizzBuzz(num);
 }

}

Output:

Please enter the length of series
20
1 ,2 ,Fizz
4 ,Buzz
Fizz
7 ,8 ,Fizz
Buzz
11 ,Fizz
13 ,14 ,FizzBuzz
16 ,17 ,Fizz
19 ,


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...