Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

language is C Pascal\'s Triangle You are tasked with writing a program that will

ID: 3818099 • Letter: L

Question

language is C

Pascal's Triangle You are tasked with writing a program that will print out Pascal's triangle to length n Information on Pascal's Triangle: https://en.wikipedia.org/wiki/Pascal%27s triangle 1 2 1 1 3 33 1 1 4 6 (https://upload.wikimedia.org/wikipedia/commons/O/0d/PascalTriangleAnimated2.gif) Each row in pascal's triangle will include two 1's (at the beginning and end except for the first row. The mid section of the row can be calculated using the previous row. A value in the midsection of the new row is calculated by adding the previous rows i 1 and i value (or sum of the two numbers directly above it). If n is 0, you will print out at least 1 row of pascal's triangle (the first). If in the case that n

Explanation / Answer

Code:

// A simple O(n^3) program for Pascal's Triangle
#include <stdio.h>

int binomialCoeff(int n, int k);

// Function to print first n lines of Pascal's Triangle
void printPascal(int n)
{
int line=0,i=0;
// Iterate through every line and print entries in it
for (line = 0; line < n; line++)
{
   // Every line has number of integers equal to line number
   for (i = 0; i <= line; i++)
   printf("%d ", binomialCoeff(line, i));
   printf(" ");
}
}

int binomialCoeff(int n, int k)
{
int i;
   int res = 1;
   if (k > n - k)
   k = n - k;
   for (i = 0; i < k; ++i)
   {
       res *= (n - i);
       res /= (i + 1);
   }
   return res;
}

// Driver program to test above function
int main(int argc, char *argv[])
{
int n;
if(argc<2)
{
printf(" Missing argument");
return 1;
}
n=atoi(argv[1]);
if(n<0)
{
printf("Invalid argument");
return 1;
}
printPascal(n+1);
return 0;
}

Output:

[~]$ gcc pa.c -o pascal
[~]$ ./pascal
Missing argument[ ~]$ ./pascal -1
Invalid argument[ ~]$ ./pascal 4
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
[ ~]$ ./pascal 10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
[]$