Programming Examples

Java program to print fibonacci series up to n terms


Write a java program which accept the number of terms form user an print the the Fibonacci series up to given terms.

Solution

import java.util.*;
class Fibonacci 
{
    public static void main(String arr[])
    {
        int a=-1,b=1,c,n;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the number of terms");
        n=sc.nextInt();
        System.out.print("Fibonacci up to "+n+" terms : ");
        for(int i=1;i<=n;i++)
        {
            c=a+b;
            System.out.print(c+"  ");
            a=b;
            b=c;
        }
    }
}
Output

Enter the number of terms

10

Fibonacci up to 10 terms : 0  1  1  2  3  5  8  13  21  34 

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad