Create an application that calculates and prints the first n Tribonacci numbers. The Tribonacci sequence is a generalisation of the Fibonacci sequence which starts with three predetermined terms (0, 0, 1) and in which every term thereafter is the sum of the three preceding terms.. The Main method is provided. Copy it and leave it as is. Your task is to define the Tribonacci method. The screen print below shows the expected output for n = 10. Your method must use a counter-controlled while loop to calculate the terms. You are not allowed to make use of collections (arrays or lists). static void Main(string[] args) { int iFirst = 0, iSecond = 0, iThird = 1; Console.Write("Enter n (n >= 3) to display the first n Tribonacci numbers: "); int n = int.Parse(Console.ReadLine()); Console.WriteLine(); Console.WriteLine(Tribonacci(iFirst, iSecond, iThird, n)); Console.Write("\nPress any key to exit..."); Console.ReadKey(); }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Q202306
{
class Program
{
static void Main(string[] args)
{
int iFirst = 0, iSecond = 0, iThird = 1;
Console.Write("Enter n (n >= 3) to display the first n Tribonacci numbers: ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine(Tribonacci(iFirst, iSecond, iThird, n));
Console.Write("\nPress any key to exit...");
Console.ReadKey();
}
private static string Tribonacci(int iFirst, int iSecond, int iThird, int n)
{
string tribonacciStr = iFirst.ToString() + "," + iSecond.ToString() + "," + iThird.ToString() + ",";
int i = 1;
while (i <= n - 3)
{
int sum = iFirst + iSecond + iThird;
iFirst = iSecond;
iSecond = iThird;
iThird = sum;
tribonacciStr += sum + ",";
i++;
}
return tribonacciStr.Substring(0, tribonacciStr.Length - 1);
}
}
}
Comments
Leave a comment