Write a program that builds the PASCAL triangle of degree N and stores it in a square matrix P of dimension N + 1.

Method:

  • Calculate and display only the values up to the main diagonal (included). Limit the degree to enter by the user to 13.
  • Construct the triangle line by line:
    • Initialize the first element and the element of the diagonal to 1.
    • Calculate the values between the initialized elements from left to right using the relation: \(P_{i, j} = P_{i-1, j} + P_{i-1, j-1}\)

Example: 
Enter the degree of the triangle (max.13) : 6
Pascal Triangle of degree 6 :
N= 0      1
N= 1      1   1
N= 2      1   2   1
N= 3      1   3   3     1
N= 4      1   4   6     4     1
N= 5      1   5   10   10   5     1
N= 6      1   6   15   20   15   6   1


Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define SIZE 50
void main()
{
 	int P[14][14];  
 	int N;         /* degree */
 	int I, J; 

 	do {
      		printf("Enter the degree of the triangle (max.13) : ");
     		scanf("%d", &N);
 	} while (N<=0 || N>13);

 	/* Construction of rows 0 to N of the triangle: */
 	/* compute the elements till the first diagonal */
 	for (I=0; I<=N; I++)
     	{
      		P[I][I]=1;
      		P[I][0]=1;
      		for (J=1; J<I; J++)
            		P[I][J] = P[I-1][J] + P[I-1][J-1];
     	}


 	printf("Pascal Triangle of degree %d :\n", N);
 	for (I=0; I<=N; I++)
    	{
     		printf(" N=%2d", I);
     		for (J=0; J<=I; J++)
          		if (P[I][J])
                		printf("%5d", P[I][J]);
     		printf("\n");
    	}
	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Width of binary trees - recursive version