Difference between revisions of "Fibonacci sequence"

From CompSciWiki
Jump to: navigation, search
Line 3: Line 3:
 
|ProblemName=Fibonacci sequence
 
|ProblemName=Fibonacci sequence
  
|Problem=Write a complete Java program Fibonacci that:<br/>
+
|Problem=<pre>Write a complete Java program Fibonacci that:<br/>
 
*prompts the user to enter an input n and cast it to integer<br/>
 
*prompts the user to enter an input n and cast it to integer<br/>
 
*get the nth fibonacci numbers using ''FOR'' loop, based on the user's input<br/>
 
*get the nth fibonacci numbers using ''FOR'' loop, based on the user's input<br/>
Line 14: Line 14:
 
<br/>
 
<br/>
 
You may assume that the user always enters correct intenger format.<br/>
 
You may assume that the user always enters correct intenger format.<br/>
 
+
<pre/>
 
|SolutionCode=
 
|SolutionCode=
 
import javax.swing.JOptionPane;<br/>
 
import javax.swing.JOptionPane;<br/>

Revision as of 23:21, 1 April 2010

{{1010PrAD

|ProblemName=Fibonacci sequence

|Problem=
Write a complete Java program Fibonacci that:<br/>
*prompts the user to enter an input n and cast it to integer<br/>
*get the nth fibonacci numbers using ''FOR'' loop, based on the user's input<br/>
*prints out the nth fibonacci number, using JOptionPane.showMessageDialog method.<br/>
<br/>
Note that the fibonacci sequence is F(0) = 1, F(1) = 1, F(n) = F(n-1) + F(n-2) for n > 1.<br/>
Example: F(5) = 1, 1, 2, 3, 5, 8<br/>
Your output should look something like<br/>
"The 5th number of the fibonacci sequence is 5."<br/>
<br/>
You may assume that the user always enters correct intenger format.<br/>
<pre/>
|SolutionCode=
import javax.swing.JOptionPane;<br/>
<br/>
public class Fibonacci <br/>
{<br/>
    public static void main(String[] args)<br/>
    {     	<br/>
 		int current = 1;<br/>
 		int previous = 0;<br/>
 		<br/>
 		int n = Integer.parseInt(JOptionPane.showInputDialog("Please enter n"));<br/>
 		<br/>
 		for(int i = 0; i < n; i++)<br/>
 		{<br/>
 			int temp = previous;<br/>
 			previous = current;<br/>
 			current = temp + previous;<br/>
 		}<br/>
 		
 		System.out.println("The " + n + "th Fibonacci number is " + current);<br/>
    }<br/>


|SideSectionTitle=...by students

|SideSection=
[[Image:OperatingSystemExample.jpg|float|267px]]
<BR>
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

|Solution=

}}