# Implementing Lucas Series in Java

In this tutorial, we will learn how to implement **Lucas series in Java**.

So what is Lucas Series?

## Lucas Series

Lucas Series is an integer sequence which is named after a mathematician François Édouard Anatole Lucas.

This series is very closely related to Fibonacci series.

The only difference is that in Fibonacci Series the sequence starts with ( 0, 1 ), while in Lucas series the sequence starts with ( 2, 1 ).

**Fibonacci series example: ** 0, 1, 1, 2, 3, 5, 8, 13…..

**Lucas Series example:** 2, 1, 3, 4, 7, 11, 18, 29…..

**Explanation**

In Lucas Series, the first number is 2 and the second number is 1.

We get the sequence by adding the two previous terms.

For example, if we want the third number in Lucas series we add the first two numbers ( i.e ) **third number** = 2 + 1 = **3**.

If we want the fifth number in the sequence we add the third and fourth terms ( i.e )** fifth number** = 3 + 4 =** 7**.

So how can we Implement Lucas series in Java? Well, it is quite simple.

Firstly we initialise two variables with 2 and 1 and perform basic Arithmetic and Swapping functions and store the values in an array.

In the end, we iterate the array and print the output to the console.

## Code for implementing Lucas Series in Java

import java.util.*; class lucas2 { public static void main(String[]args) { Scanner scan = new Scanner(System.in); int first = 2; int second = 1; int temp = 0; System.out.print("Enter the number of terms you want to print: "); int number = scan.nextInt(); int []arr = new int[number]; if(number == 1) { System.out.println(2); System.exit(0); } else if(number == 2) { System.out.println("2,1"); System.exit(0); } arr[0] = 2; arr[1] = 1; for(int i = 2; i < number; i++) { temp = first + second; arr[i] = temp; first = second; second = temp; } System.out.print("The Lucas Series is: "); for(int i = 0; i < number; i++) { System.out.print(arr[i]+","); } } }

#### Output:

Enter the number of terms you want to print: 5 The Lucas Series is: 2,1,3,4,7

Enter the number of terms you want to print: 10 The Lucas Series is: 2,1,3,4,7,11,18,29,47,76

Hope you understood the code 🙂

Any questions please feel free to drop in your comments.

You can also check:

## Leave a Reply