1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java - calculate nth Fibonacci number

  1. Sep 7, 2012 #1
    1. The problem statement, all variables and given/known data

    Hello everyone, I am trying to write a java program that asks the user to input a number n, and the computer calculates the nth Fibonacci number. I am supposed to use a loop to calculate the problem.

    My question is, how do I set up the loop to calculate the nth Fibonacci number? I know how to do all of the program except the loop.

    2. Relevant equations

    I want to use the "for" loop.

    3. The attempt at a solution

    import java.util.Scanner;

    public class Assignment2 {
    public static void main(String [] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number n in order to calculate the nth Fibonacci number: ");
    int n = input.nextInt();

    for(int i = 0; i;){}

    System.out.println("The " + n + "th Fibonacci number is: ");

    }
    }
     
  2. jcsd
  3. Sep 7, 2012 #2

    Mark44

    Staff: Mentor

    When you post code, put it inside [noparse]
    Code (Text):
     
    [/noparse] tags. This makes your code easier to read, by preserving your indentation (if you used any).

    You can't write a program to calculate Fibonacci numbers if you don't know how to calculate them yourself. What are the first few numbers in a Fibonacci sequence?
     
  4. Sep 8, 2012 #3
    a1 = 0, a2 = 1, a3 = 1, a4 = 2, a5 = 3, a6 = 5, ....etc. adding the last two numbers to get the nth number.
     
  5. Sep 8, 2012 #4

    gabbagabbahey

    User Avatar
    Homework Helper
    Gold Member

    Usually the indices start at zero, so that [itex]F_0=0[/itex], [itex]F_1=1[/itex], [itex]F_2=1[/itex], [itex]F_3=2[/itex],etc.

    I would suggest that you store all calculated Fibonacci numbers in an array of Integers. To start with, you will need to initialize the array to include [itex]F_0[/itex] and [itex]F_1[/itex]. Then, to calculate the nth number, you first look in the array to see if it has already been calculated; if yes then simply output that entry in the array, if no, then start with the last 2 entries in the array an calculate and store (in the array) all the remaining numbers up until the nth number.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook