In this tutorial, you will learn how to write a program to print Pascal’s Triangle in C. Before that you should be familiar with the following topic in C programming.
Pascal’s triangle is one of the important examples that is taught to the student. The number outside Pascal’s triangle is zero (0), which is not visible. It is a pattern where the triangle starts from 1 at the top and below is the addition of the upper level as you can see in the figure below. The addition continues until the required level is reached.
Pascal Triangle Program in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /c program to print pascal's triangle #include <stdio.h> int main() { int rows, coef = 1, s, i, j; printf("Enter the number of rows: "); scanf("%d", &rows); for (i = 0; i < rows; i++) { for (s = 1; s <= rows - i; s++) printf(" "); for (j = 0; j <= i; j++) { if (j == 0 || i == 0) coef = 1; else coef = coef *(i - j + 1) / j; printf("%3d", coef); } printf("\n"); } return 0; } |
Output:
1 2 3 4 5 6 | 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 |