Fibonacci Numbers

From CompSciWiki
Revision as of 10:12, 8 April 2010 by JustinS (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

This problem involves you writing a program that will take in which Fibonacci number you want to print out and then iteratively calculates the number. Remember that the algorithm for Fibonacci numbers is Fibonacci[n] = Fibonacci[n-1] + Fibonacci[n-2] where Fibonacci[0] = 0 and Fibonacci[1] = 1. Remember you are going to want to declare your array but not specify the size until you take in your input with JOptionPane:
JOptionPane.showInputDialog()
Remember that you can convert Strings that are numbers to ints using:
Integer.parseInt()
Print out the number that is specified to the console with:
System.out.println();

Don't forget to import javax.swing.JOptionPane"! You can assume the user will give appropriate input for this problem.

 

...by students

I remember being back in COMP1010 and looking at the Fibonacci number problem and being slightly intimidated. This is a very common problem that instructors like to give to their students and for good reason. It requires you to take a bunch of different skills you have learned so far and apply them all together. I remember trying to think of ways to solve this problem and the best way I found to do it was by breaking it down into smaller tasks and solving those first. By taking small steps towards the final solution and consistently compiling my code to see if it worked, I was able to solve this problem. This is a technique that I have used throughout my four years in Computer Science and it has become only more valuable as the classes got more difficult. If you take every problem slowly and methodically, you will eventually solve the problem.

Solution

To solve this problem we first start by declaring the variables that we will need. We will need an array to store our Fibonacci numbers, a String to store our input, an int to store our parsed input and another int to store out output. Remember to not initialize our variables yet other then the output:
int output = 0;
We do this because otherwise the compiler will yell at us. The next step is to take in our input from the user and convert it from a string to an int. We do this by:
 input = JOptionPane.showInputDialog ("Please enter the Fibonacci number you want to calculate:");
 inputNum = Integer.parseInt(input);

The next thing we want to do is to check the input for its value. If the input is either 1 or 2 we know without calculating what the Fibonacci number is based on the formula that was provided. A simple if-else block will solve our problem:

if (inputNum == 1)
  output = 0;
else if (inputNum == 2)
  output = 1;

Code

Solution Code

Back to the Program-A-Day homepage