Loop Exercises
Write a C program to print pascal triangle up to n rows using loop. Logic to print Pascal triangle in C programming. How to print Pascal triangle of n rows using loop in C program.
Required knowledge
Basic C programming, For loop, While loop, Nested loop, Functions
Pascal Triangle
Pascal triangle is a triangular number pattern named after famous mathematician Blaise Pascal.
For example Pascal triangle with 6 rows.
Logic to print pascal triangle
To find nth term of a pascal triangle we use following formula.
Where n is row number and k is term of that row.
Step by step descriptive logic to print pascal triangle.
- Input number of rows to print from user. Store it in a variable say num.
- To iterate through rows, run a loop from 0 to num, increment 1 in each iteration. The loop structure should look like for(n=0; n
- Inside the outer loop run another loop to print terms of a row. Initialize the loop from 0 that goes to n, increment 1 in each iteration.
- Inside the inner loop use formula term = fact(n) / (fact(k) * fact(n-k)); to print current term of pascal triangle.
Here, fact() is a function defined to find factorial of a number.
Program to print Pascal triangle
/**
* C program to print Pascal triangle up to n rows
*/
#include <stdio.h>
/* Function definition */
long long fact(int n);
int main()
{
int n, k, num, i;
long long term;
/* Input number of rows */
printf("Enter number of rows : ");
scanf("%d", &num);
for(n=0; n<num; n++)
{
/* Prints 3 spaces */
for(i=n; i<=num; i++)
printf("%3c", ' ');
/* Generate term for current row */
for(k=0; k<=n; k++)
{
term = fact(n) / (fact(k) * fact(n-k));
printf("%6lld", term);
}
printf("\n");
}
return 0;
}
/**
* Function to calculate factorial
*/
long long fact(int n)
{
long long factorial = 1ll;
while(n>=1)
{
factorial *= n;
n--;
}
return factorial;
}
The statement printf("%3c", ' '); is used to print 3 white spaces and is equivalent to printf(" ");.
The statement printf("%6lld", term); prints the current term with 6 character width.
To print a long long type value I have used %lld format specifier.
In the fact() function I have added ll suffix while declaring long long factorial = 1ll;. Since 1 is an integer variable, hence to tell the compiler explicitly that store 1 as long long type I have added the suffix.
