Write a program that builds and displays Pascal's triangle by calculating the binomial coefficients:
Example:
Enter the degree of the triangle (max.13) : 6
Pascal Triangle of degree 7 :
N= 1 1
N= 2 1 1
N= 3 1 2 1
N= 4 1 3 3 1
N= 5 1 4 6 4 1
N= 6 1 5 10 10 5 1
N= 7 1 6 15 20 15 6 1
We will not use a table, ie. it will be necessary to calculate the coefficients according to the formula below, while defining and using the adequate functions.
\(C_p^q=\frac{p!}{q!(p-q)!}\)
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
double FACT(int N)
{
double RESULT;
for (RESULT = 1.0; N>0; N--)
RESULT *= N;
return RESULT;
}
double C(int P, int Q)
{
return FACT(P) / (FACT(Q)*FACT(P - Q));
}
void Row(int P)
{
int Q;
for (Q = 0; Q <= P; Q++)
printf("%6.0f", C(P, Q));
printf("\n");
}
void TRIANGLE(int ROWS)
{
int P;
for (P = 0; P<ROWS; P++)
Row(P);
}
void main()
{
int N;
printf("Enter the number of lines N : ");
scanf("%d", &N);
TRIANGLE(N);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Fibonacci sequence