* Write a Java program that calculates and displays the
Fibonacci numbers
* First prompt the user to input a number, N
* Then use a for loop to calculate and display the first N
fibonocci numbers
* For example, if the user enters 5, the output should be:
* 1, 1, 2, 3, 5
*
* if the user enters 10, the output should be:
* 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int n;
n=s.nextInt(); //Taking the input
int first = 1, second = 1; //Since first 2 terms are 1 and 1
//For loop
for(int i=0;i<n;i++){
System.out.print(first + " ");
int temp = first + second; //next term in the sequence is sum of last two
first = second; //For next step 2nd term is first term
second = temp; //For next step the next term is the second term
}
}
}
Get Answers For Free
Most questions answered within 1 hours.