Home  >  Article  >  Backend Development  >  How to print integers in Pascal triangle form using C language?

How to print integers in Pascal triangle form using C language?

WBOY
WBOYforward
2023-08-28 23:53:041206browse

Pascal's triangle is a way to represent integers in the form of triangles. One well-known representation is using the binomial equation. We can do this using combinations and factorials.

Building Pascal's Triangle

All values ​​outside the triangle are treated as zero (0). The first line is 0 1 0, and while only 1 occupies a space in Pascal's triangle, 0 is invisible. The second row is obtained by adding (0 1) and (1 0). The output is sandwiched between two zeros. This process continues until the desired level is reached.

From a programming perspective, Pascal's triangle is defined as an array built by adding adjacent elements in previous rows.

How to print integers in Pascal triangle form using C language?

Program 1

In this program, we will print the integers in Pascal's triangle in the form of an array -

Online Demonstration

#include <stdio.h>
int fact(int);
int main(){
   int i,rows,j;
   printf("enter no of rows :");
   scanf("%d",&rows);
   for (i = 0; i < rows; i++){
      for (j = 0; j <= (rows- i - 2); j++)
         printf(" ");
      for (j = 0 ; j <= i; j++)
         printf("%d ",fact(i)/(fact(j)*fact(i-j)));
      printf("</p><p>");
   }
   return 0;
}
int fact(int n){
   int a;
   int sum = 1;
   for (a = 1; a <= n; a++)
      sum = sum*a;
   return sum;
}

Output

Enter no of rows :5
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Program 2

Here we will see the printing of integers in the form of Pascal’s triangle without using arrays

Live Demonstration

#include<stdio.h>
int main(){
   int num,row,i;
   printf("Enter the number of rows: ");
   scanf("%d",&num);
   for(row=1; row<=num; row++){
      int a=1;
      for(i=1; i<=row; i++){
         printf("%d ",a);
         a = a * (row-i)/i;
      }
      printf("</p><p>");
   }
   return 0;
}

Output

Enter the number of rows: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

The above is the detailed content of How to print integers in Pascal triangle form using C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete