Let us create an interesting program. A program that prints “fizz” and “Buzz” according to the multiplies of a number.
For eg: “Fizz” prints for multiplies of a number. “Buzz”
prints for multiplies of another number. “FizzBuzz” prints for multiplies of
both numbers.
Program implementation:
Let us discuss the program logic.
- · First, get the number of elements from the user.
- · Next, get two numbers(fn,sn) one by one for printing Fizz and Buzz.
- · Using a for loop, do the activity repeated until i<=n.
- · Check the ‘i’ value with fn,sn. Based on the value, print “Fuzz”,“buzz” and number accordingly.
Program:
o
To write the program, follow the steps.
- · First import the built in package java.util.Scanner.
- · Create a public class with main() function.
- · Create a scanner object to read the input from the user.
- · Using for loop, check the number and print the output.
Here is the program.
import java.util.Scanner;
public class FizzBuzzPrint {
public static void
main(String[] args) {
Scanner s1 =
new Scanner(System.in);
System.out.println("Enter
the number of elements");
int n =
s1.nextInt();
System.out.println("Enter the first number");
int fn =
s1.nextInt();
System.out.println("Enter the second number");
int sn =
s1.nextInt();
for (int i =
1; i <= n; i++) {
if (i % fn
== 0 && i % sn == 0) {
System.out.println("FizzBuzz");
} else if
(i % fn == 0) {
System.out.println("Fizz");
} else if
(i % sn == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}
Output:
Compile the program to get the class file.
C:\raji\blog>javac FizzBuzzPrint.java
Run the program to get the output.
C:\raji\blog>java FizzBuzzPrint
Enter the number of elements
20
Enter the first number
2
Enter the second number
6
1
Fizz
3
Fizz
5
FizzBuzz
7
Fizz
9
Fizz
11
FizzBuzz
13
Fizz
15
Fizz
17
FizzBuzz
19
Fizz
That’s all. The program to implement FizzBuzz print
according to the number was implementing successfully. Keep coding!!!!
No comments:
Post a Comment