Pin It

Write a Java program to print Jacobsthal Sequence.

Program to implement Jacobsthal sequence in Java.

The Jacobsthal sequence starts with numbers 0 and 1. After that each successive number is sum of previous number plus twice the number previous to previous number.

package com.hubberspot.java.sequences;

import java.util.Scanner;

public class Jacobsthal {

    public static void main(String[] args) {
       
        int firstNumber = 0;
        int secondNumber = 1;
                
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the number of terms for Jacobsthal sequence : ");
        
        int noOfTerms = scanner.nextInt();
        int nextNumber;
        
        System.out.print( firstNumber + " " + secondNumber);
        
        for(int i = 1; i <= noOfTerms - 2; i++) { 
            
            nextNumber = secondNumber + 2 * firstNumber;
            System.out.print(" " + nextNumber);
            firstNumber = secondNumber;
            secondNumber = nextNumber;
            
        }        

    }

}


Output of the program : 

 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot