Coders Packet

How to print fibonacci series using for loop in Java.

By Sweta Sinha

This project is about fibonacci series using for loop in Java which are displayed in following sequence. Fibonacci series=0,1,1,2,3,5,8,13,21,34

Fibonacci series using for loop in Java

The fibonacci series are the series of numbers where a number is the sum of the previous two numbers.If we start with 0 and 1 it will go 0,1,1,2,3,5,8,13,21 and so on. In this project we will learn to display fibonacci series in Java using for loop. Here we will learn to show the fibonacci series upto a specific number.The first two numbers of the fibonacci series are 0 followed by 1.Fibonacci series generates subsequent number by adding previous two numbers.

import java.io.*;
public class Fibonacci
{
  public static void main(String[] args)
  {
    int count=7,num1=0,num2=1;
    System.out.print("Fibonacci Series of "+count+"numbers:");
    
    for(int i=1;i<=count;++i)
    {
      System.out.print(num1+" ");
      
/*On each iteration,we are assigning second number to the first number and assigning the sum of last two numbers to the second number*/

      int sumOfPrevTwo=num1+num2;
      num1=num2
      num2=sumOfPrevTwo;
    }
   }
}

Output:
Fibonacci series of 7 numbers are:0,1,1,2,3,5

 

Download project

Reviews Report

Submitted by Sweta Sinha (Sweta321)

Download packets of source code on Coders Packet