Program to Print Fibonacci Series upto nth value

 


Code:

import java.util.Scanner;
public class fibonacci
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int sum = 0, n;
int a = 0;
int b = 1;
System.out.println("Enter the nth value: ");
n = sc.nextInt();
System.out.println("Fibonacci series: ");
while(sum <= n)
{
System.out.print(sum + " ");
a = b; // swap elements
b = sum;
sum = a + b; // next term is the sum of the last two terms
}
}
}

Output:






AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page