Print numbers from 1 to 20, where print "Fizz" for multiple of 3, "Buzz" for multiple of 5, "FizzBuzz" for multiple of 3 and 5, and print numbers for others.
Code:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Code:
public class PrintMultiple {
public static void main(String args[])
{
printMulti();
}
public static void printMulti()
{
for(int i=1;i<=20;i++)
{
//Method one
/*if(i%3==0)
System.out.println("Fizz");
else if(i%5==0)
System.out.println("Buzz");
else if(i%15==0)
System.out.println("FizzBuzz");
else
System.out.println(i);*/
//Method Two
if(i%3==0 && i%5!=0)
System.out.println("Fizz");
if(i%5==0 && i%3!=0)
System.out.println("Buzz");
if(i%15==0) /* or else if(i%3==0 && i%5==0)*/
System.out.println("FizzBuzz");
if(i%3!=0 && i%5!=0 && i%15!=0)
System.out.println(i);
}
}
}
Output :1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
No comments:
Post a Comment