|
|
Line 7: |
Line 7: |
| |SideSection= | | |SideSection= |
| [[Image:Wiki_array01.jpg|float|267px]] | | [[Image:Wiki_array01.jpg|float|267px]] |
− | <BR>
| |
− | Taken from http://www.flickr.com/photos/daniello/565304023/
| |
− |
| |
| An image or By Students section | | An image or By Students section |
| | | |
Revision as of 12:38, 6 April 2010
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. Print out the number that is specified.
|
|
Introducing Arrays
An image or By Students section
|
Solution
The solution...
|
Code
Solution Code
import javax.swing.JOptionPane;
public class Fibonacci
{
public static void main (String[]args)
{
int[] fibonacci; //This is the array that will contain the Fibonacci numbers
String input; //This contains the input from the JOptionPane
int inputNum; //This is the parsed number from the input String.
int output = 0; //This is the output to be printed to the console.
//This will generate and show the input dialog box to take in the Fibonacci number that you want to display.
input = JOptionPane.showInputDialog ("Please enter the Fibonacci number you want to calculate:");
inputNum = Integer.parseInt(input);
//Check the inputNum and depending on the starting value...
if (inputNum == 1)
output = 0;
else if (inputNum == 2)
output = 1;
else if (inputNum > 2)
{
//This initilizes the fibonacci array and sets the starting values.
fibonacci = new int[inputNum];
fibonacci[0] = 0;
fibonacci[1] = 1;
//You start this loop at 2 because you have already calculated the starting two values and you want
//to start on the third index of the array.
for (int i = 2; i < inputNum; i++)
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
output = fibonacci[inputNum - 1];
}
System.out.println ("The number is: " + output);
}
}
|
Back to the Program-A-Day homepage