Ad Code

Generate Fibonacci series using Java For/While loop.

Program-
import java.util.*;
public class Fibonacci {
 public static void main(String[] args){
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter a number : ");
 int n =sc.nextInt();
if(n==1){
 System.out.println("0");
 }
 else if(n==2){
 System.out.println("0 1");
 }
 else if(n>2){
 int a=0,b=1;
 System.out.print("0 1 ");
 for(int i=3;i<=n;i++){
 int temp = a+b;
 System.out.print(temp+" ");
 a=b;
 b=temp;
 }
 }
 else{
 System.out.println("Invalid input");
}
 }
}
Reactions

Post a Comment

0 Comments