ICSE Class 10 Computer Applications Question 22 of 69

Iterative Constructs in Java — Question 22

Back to all questions
22
Question

Question 18

Write a program to read the number n using the Scanner class and print the Tribonacci series: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81 ...and so on.
Hint: The Tribonacci series is a generalisation of the Fibonacci sequence where each term is the sum of the three preceding terms.

import java.util.Scanner;

public class KboatTribonacci
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter no. of terms : ");
        int n = in.nextInt();
        
        if(n < 3)
            System.out.print("Enter a number greater than 2");
        else    {
            int a = 0, b = 0, c = 1;
            System.out.print(a + " " + b + " " + c);
        
            for (int i = 4; i <= n; i++) {
                int term = a + b + c;
                System.out.print(" " + term);
                a = b;
                b = c;
                c = term;
            }
        }
    }
}
Output
BlueJ output of KboatTribonacci.java
Answer