Categories
Class 11 Class 12

Hailstone Sequence Program in Java

Write a program in Java to generate the Hailstone Sequence for a given number.

The Hailstone Sequence of numbers can be started from a given positive integer N.

The remaining terms of the sequence can be evaluated by applying the following rules:

  1. If N = 1, then the sequence terminates.
  2. If N is even, then the next term of the sequence is N / 2.
  3. If N is odd, then the next term in the sequence is 3 × N + 1.

For example:
INPUT:
N = 13
OUTPUT:
40 20 10 5 16 8 4 2 1

Use a recursive method to generate and display the Hailstone Sequence by passing N as a parameter to the method.

Display an appropriate message if the number N <= 0.

import java.io.*;
class Hailstone{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        hailstoneSequence(n);
    }
    public static void hailstoneSequence(int n){
        if(n <= 0)
            System.out.println("Invalid Input!");
        else if(n == 1)
            return;
        else if(n % 2 != 0){
            int next = n * 3 + 1;
            System.out.print(next + " ");
            hailstoneSequence(next);
        }
        else{
            int next = n / 2;
            System.out.print(next + " ");
            hailstoneSequence(next);
        }
    }
}

2 replies on “Hailstone Sequence Program in Java”

Leave a Reply