In one of the online assessment test a program is asked as to print the numbers from 1 to n where if the number is divisible by 3 then print "Fizz" and if number is divisible in 5 then print "Zeera" and if number is divisible completely by 3 and 5 then print "FizzZeera".
The below program shows the java program when the input number is 35.
package com.rohan.test;
public class Test {
public static void main(String[] args) {
printNumbers(35);
}
public static void printNumbers(int n) {
for(int i = 1; i<=n; i++) {
int flag1 = 0, flag2 = 0;
if(i%3 == 0) {
flag1=1;
}
if(i%5 == 0) {
flag2 = 1;
}
if(flag1 == 1 && flag2 == 1) {
System.out.println("FizzJeera");
}
else if(flag1 == 1 && flag2 == 0) {
System.out.println("Fizz");
}
else if(flag1 == 0 && flag2 == 1) {
System.out.println("Jeera");
}
else {
System.out.println(i);
}
}
}
}
The output of the given program is as below:
1
2
Fizz
4
Jeera
Fizz
7
8
Fizz
Jeera
11
Fizz
13
14
FizzJeera
16
17
Fizz
19
Jeera
Fizz
22
23
Fizz
Jeera
26
Fizz
28
29
FizzJeera
31
32
Fizz
34
Jeera
hi rohan anand(Symphony Employee).
ReplyDeletecorrect above one sentence.. if number is divisible completely by 3 and 3 then print "FizzZeera".
correct one is: if number is divisible completely by 3 and 5 then print "FizzZeera".
Hi Naresh,
DeleteCorrected. Thanks for pointing out the mistake.