title
i’m trying to program pascal’s triangle in c# and i cant understand whats wrong with the code,
this is what i wrote:
static void Main(string[] args)
{
int numrows = int.Parse(Console.ReadLine());
PascalsTriangle(numrows);
}
static void PascalsTriangle(int numRows)
{
List<int> triangle = new List<int>();
List<int> trianglestorage = new List<int>();
Console.WriteLine(" " + string.Join("", triangle));
for (int i = 0; i < numRows; i++)
{
Console.WriteLine();
triangle.Add(1);
triangle.Insert(0, 1);
Console.WriteLine(string.Join(", ", triangle)); // this is the last normal output and the system shows memory overflow error inside the loop. for some reason it goes on forever even though triangle.Count is now 3 and it should repeat only twice
for (int j = 0; j < triangle.Count() - 1; j++)
{
trianglestorage.Add(triangle[j] + triangle[j+1]);
}
triangle = trianglestorage;
}
}
currently the output is looking like this:
1
1, 1
1, 2, 1
then the program just keeps on going without outputting anything and eventually it closes due to memory overflow
New contributor
BorZafror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1