KnowledgeBoat Logo

Computer Applications

Write a program to read the number n via 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.

Java

Java Iterative Stmts

10 Likes

Answer

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 Write a program to read the number n via 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.

Answered By

2 Likes


Related Questions