Nth Fibonacci Number in Java: Explanation & Practice

Find the nth Fibonacci number

Problem summary

Write a program that calculates the nth Fibonacci number (0, 1, 1, 2, 3, 5, 8...).

Starter code

public class Main {
    public static void main(String[] args) {
        int n = 10; // Test case 1
        
        // Calculate nth Fibonacci number (0-indexed)
        // Print: Fibonacci: <result>
    }
}

Expected output and test cases

  • F(10) = 55
    Fibonacci: 55
  • F(6) = 8
    Fibonacci: 8
  • F(0) = 0
    Fibonacci: 0

Hints

  1. F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2)
  2. Use two variables to track previous values
  3. Iterate n times, updating both values each time

Related Control Flow exercises

Practice all Control Flow exercises · Run this idea in the Java compiler