I am trying to write a function to print out Pascal's triangle up to the step that the user inputs. The program works until step 5, and prints out 0 1 4 0 4 1 0 instead of 0 1 4 6 1 0 which is expected. It takes two values from another list, which are both 3 at the time, and adds them so i am not sure how it is changed to 0.
Code:
static void PascalsTri(int input)
{
//Declare lists starting at 0 1 0
int counter = 0;
int[] start = { 0, 1, 0 };
List<int> TriList = new List<int>(start);
List<int> TempTriList = new List<int>();
//Check if input is possible
if(input < 1)
{
return;
}
//Write starting list to console
Console.WriteLine(string.Join(" ", TriList));
//Run the function as many times as the user input
for(int i = 1; i < input; i++)
{
//Start off with the first two digits
TempTriList.Add(0);
TempTriList.Add(1);
//Loop through writing the rule for as many numbers as there are
while(counter < i)
{
//Takes the previous number and adds it to the correlating number
TempTriList.Insert(counter+1, TriList[counter] + TriList[counter+1]);
counter++;
}
TempTriList.Add(0);
TriList.Clear();
//Records the output in the permanent list, and prints it to the console
foreach(int j in TempTriList)
{
TriList.Add(TempTriList[j]);
}
TempTriList.Clear();
counter = 0;
Console.WriteLine(string.Join(" ", TriList));
}
}