Java Program demonstrating the Fibonacci Sequence

The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

in which the next number is found by adding up the two numbers before it.

A Formula can be generated for this like

Xn= Xn-1 + Xn-2

where:

  • xn is term number “n”
  • xn-1 is the previous term (n-1)
  • xn-2 is the term before that (n-2)

Here is the Java Program creating a Fibonacci Sequence till 25 digits. An array is used to store the Fibonacci Sequence using  a for loop.


public class FibonacciSeriesDemo {

	public static void main(String[] args) {

	//Setting the number of elements to generate in the fibonacci series

	int limit = 25;

	long[] fibonacciSeries = new long[limit];

	// Initialize the First two elements of the Fibonacci Series
	fibonacciSeries[0] = 0;

	fibonacciSeries[1] = 1;

	//Create the Fibonacci series and store it in an array

	for(int i=2; i < limit; i++){
		fibonacciSeries[i] = fibonacciSeries[i-1] + fibonacciSeries[i-2];
	}

	//print the Fibonacci series numbers
	System.out.println("Fibonacci Series upto " + limit);
        System.out.println();
	for(int i=0; i< limit; i++){

		System.out.print(fibonacciSeries[i] + " ");
	}

}//main

}

Snapshot of the output

JavaFibonacciSeriesDemoProgramOutput

Multiplication Table in Java by taking the Number from the Command Line


class MultiTab
{
	public static void main(String[] args)
	{
		int i;
		int num = Integer.parseInt(args[0]);
		for(i=1; i<=10; i++)
		{
			System.out.println(num+ " * " +i+ " = "+num * i);
		}
	}
}

Snapshot of the o/p

Multiplication Table in Java

This is a very basic program But for a beginner it is worth trying.

And it also makes us aware about the power of for loop which can repeat so many times within a second.

public class MulTable
{
	public static void main(String[] args)
	{
		int i;
		int num = 9;
		for(i=1; i<=10; i++)
		{
			System.out.println(num+ " * " +i+ " = "+num * i);
		}
	}
}

Snapshot of the o/p