I'm a total beginner. I'm trying to find Tribonnaci numbers but I don't understand why I'm getting this error.
System.IndexOutOfRangeException
btw that's a method i didnt put all the line but first line was public static void TribonacciNumbs(int n)
edit: thanks to replies i undertand i was creating a new array instead of adding new value which what i want to do
i changed for loop as these lines
Array.Resize(ref tribo, i+1);
num = tribo[i-1]+tribo[i-2]+tribo[i-3];
tribo[i]=num;
now it works
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace TestArea
{
internal class Program
{
static void Main(string[] args)
{
TribonacciNumbs(4);
Console.ReadLine();
}
public static void TribonacciNumbs(int n)
{
int[] tribo;
tribo = new int[] { 0, 1, 1 };
int num=0;
if (n >= 3)
{
for (int i = 3; i <= n; i++)
{
num = tribo[i - 1] + tribo[i - 2] + tribo[i - 3];
tribo = new int[] {num};
}
}
if (n == 0)
{
Console.WriteLine(0);
}else if (n == 1)
{
Console.WriteLine(1);
}else if(n == 2)
{
Console.WriteLine(1);
}else Console.WriteLine(tribo[n]);
}
}
}