Control Flow & Loops

Practice: FizzBuzz & Number Problems

15 min Lesson 10 of 14

Practice: FizzBuzz & Number Problems

You have now learned all the control-flow and loop tools Java offers. This final lesson puts everything together through three classic problems you will encounter in technical interviews and real code reviews: FizzBuzz, prime-number detection, and factorial calculation. Working through them trains the habit of translating plain-English requirements into clean, correct Java.

Problem 1 — FizzBuzz

Task: Print the numbers from 1 to 100. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both 3 and 5 print FizzBuzz.

The key insight is order of conditions. The combined check (% 3 == 0 && % 5 == 0) must come first, otherwise it will never be reached:

public class FizzBuzz { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 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.println(i); } } } }
Common mistake — wrong order: If you put the % 3 == 0 check before the combined check, the number 15 prints Fizz and never reaches FizzBuzz. Always test the most specific condition first.

A clean alternative builds the output string before printing, which avoids repeating System.out.println:

for (int i = 1; i <= 100; i++) { String result = ""; if (i % 3 == 0) result += "Fizz"; if (i % 5 == 0) result += "Buzz"; if (result.isEmpty()) result = String.valueOf(i); System.out.println(result); }
Why the string-building approach scales: If the requirements later add a rule for multiples of 7 ("Jazz"), you just append one more if instead of rewriting every branch. Writing code that is easy to extend is a sign of experience.

Problem 2 — Prime Number Detection

A prime number is greater than 1 and has no divisors other than 1 and itself. The brute-force approach checks every number from 2 up to n - 1, but we only need to check up to Math.sqrt(n): if n has a factor larger than its square root, the matching smaller factor has already been found.

public class Primes { public static boolean isPrime(int n) { if (n < 2) return false; // 0 and 1 are not prime if (n == 2) return true; // 2 is the only even prime if (n % 2 == 0) return false; // quickly discard other evens for (int i = 3; i * i <= n; i += 2) { // check odd divisors only if (n % i == 0) return false; } return true; } public static void main(String[] args) { System.out.println("Primes up to 50:"); for (int i = 2; i <= 50; i++) { if (isPrime(i)) { System.out.print(i + " "); } } // Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 } }
Why i * i <= n instead of i <= Math.sqrt(n)? Both are correct. The multiplication form avoids a floating-point square root call on every iteration, keeping the loop slightly faster. For the numbers you will deal with as a beginner the difference is invisible, but it is the idiomatic choice in Java.

Problem 3 — Factorial

The factorial of a non-negative integer n (written n!) is the product of all positive integers from 1 to n. By definition, 0! = 1.

Iterative version — straightforward and efficient:

public class Factorial { public static long factorial(int n) { if (n < 0) throw new IllegalArgumentException("n must be non-negative"); long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } public static void main(String[] args) { for (int i = 0; i <= 10; i++) { System.out.println(i + "! = " + factorial(i)); } } }

Notice the return type is long rather than int13! (6,227,020,800) overflows a 32-bit int, so using long gives you safe results up to 20!.

Recursive version for reference: Factorial is also a classic example of recursion. A recursive solution calls itself: factorial(n) = n * factorial(n - 1). The iterative form above is preferred in production because it does not risk a stack overflow for large inputs and is easier to reason about.

Putting It All Together

All three problems follow the same pattern you have practiced throughout this tutorial:

  1. Read the rule in plain English.
  2. Choose the right loop (for for a known range, while when the exit condition is dynamic).
  3. Inside the loop, write if/else if/else conditions in order from most specific to least specific.
  4. Use break or early return to stop as soon as you have an answer — do not keep looping unnecessarily.
Interview tip: When asked a FizzBuzz-style problem, talk through your reasoning out loud before typing. Interviewers care as much about how you think as whether you get the right answer on the first try.

Summary

You have now completed the Control Flow & Loops tutorial. FizzBuzz taught you correct condition ordering and string-building patterns. Prime detection showed how a single mathematical observation (square-root bound) turns a slow loop into a fast one. Factorial demonstrated safe integer sizing and the value of iterative over recursive solutions for simple accumulations. These three problems are a strong foundation for every algorithm challenge ahead.