Reputation: 23
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));
}
}
Upvotes: 2
Views: 307
Reputation: 186668
If you want to print Pascal Triangle line after line you can just loop while computing next
line in the process (fiddle)
Code:
static void PascalTri(int rowsToPrint) {
// 1st current line
int[] current = new int[] { 0, 1, 0 };
Console.WriteLine(string.Join(" ", current));
// we compute all the other lines in a simple loop
for (int r = 1; r < rowsToPrint; ++r) {
// next line is 1 number longer than current
int[] next = new int[current.Length + 1];
// compute next line items
for (int c = 0; c < current.Length - 1; ++c)
next[c + 1] = current[c] + current[c + 1];
// after computation, next line becomes current one
current = next;
// finally, we print the line
Console.WriteLine(string.Join(" ", current));
}
}
Demo:
PascalTri(10);
Outcome:
0 1 0
0 1 1 0
0 1 2 1 0
0 1 3 3 1 0
0 1 4 6 4 1 0
0 1 5 10 10 5 1 0
0 1 6 15 20 15 6 1 0
0 1 7 21 35 35 21 7 1 0
0 1 8 28 56 70 56 28 8 1 0
0 1 9 36 84 126 126 84 36 9 1 0
Upvotes: 1
Reputation: 2454
That had me stumped for a while, too. Then I realized that a single line of code in your foreach
is wrong.
TriList.Add(TempTriList[j]);
It should be:
TriList.Add(j);
The variable "j" isn't an index, but the array value itself. Once you make that change, it all works.
This code might be better arranged if it used a recursive method, but since what you have works (now), I'd leave it. Making that change to use recursion can be difficult and far beyond the scope of this question.
Upvotes: 1