Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

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 : 

 
 
© 2021 Learn Java by Examples Template by Hubberspot