Program to print Pascal’s triangle

Program to print Pascal’s triangle is discussed here. Pascal’s triangle is a triangular array of the binomial coefficients. 

The numbers outside Pascal’s triangle are all “0”. These “0s” are very important for the triangular pattern to work to form a triangular array. The triangle starts with a number “1” above, and any new number added below the upper number “1” is just the sum of the two numbers above, except for the edge, which is all “1”. 

 

pascal's trianglerow 0 =1
row 1 = (0+1), (1+0) = 1, 1
row 2 = (0+1), (1+1), (1+0) = 1, 2, 1
row 3 = (0+1), (1+2), (2+1), (1+0) = 1, 3, 3, 1
row 4 = (0+1), (1+3), (3+3), (3+1), (1+0) = 1, 4, 6, 4, 1
row 5 = (0+1), (1+4), (4+6), (6+4), (4+1),(1+0) = 1, 5, 10, 10, 5, 1
row 6 = (0+1), (1+5), (5+10), (10+10), (10+5), (5+1), (1+0) = 1, 6, 15, 20, 15, 6, 1

Program to print pascal's triangle

//  C program to print pascal’s triangle

#include
int main()
{
int rows, coef = 1, space, i, j;
printf(“\nEnter the number of rows : “);
scanf(“%d”,&rows);
printf(“\n”);

for(i=0; i<rows; i++)
{
for(space=1; space <= rows-i; space++)
printf(” “);

for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;

printf(“%4d”, coef);
}
printf(“\n\n”);
}

return 0;
}

//  C++ program to print pascal’s triangle

#include
using namespace std;
int main()
{
int rows, coef = 1, space, i, j;
cout << “\nEnter the number of rows : “;
cin >> rows;
cout << endl;

for(i=0; i<rows; i++)
{
for(space=1; space <= rows-i; space++)
cout << ” ” ;

for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;

cout << coef << ” “;
}
cout << endl;
cout << endl;
}

return 0;
}

//  Java program to print pascal’s triangle

import java.util.*;

class Main
{
public static void main(String args[])
{
int i,j, space;
int coef, rows;
coef = 1;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the number of rows : “);
rows = sc.nextInt();

for(i=0; i<rows; i++)
{
for(space=1; space <= rows-i; space++)
System.out.print(” “) ;

for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;

System.out.print(coef + ” “);
}
System.out.println(“\n”);
}
}
}

# Python program to print pascal’s triangle

n=int(input(“Enter number of rows: “))
a=[]
for i in range(n):
a.append([])
a[i].append(1)
for j in range(1,i):
a[i].append(a[i-1][j-1]+a[i-1][j])
if(n!=0):
a[i].append(1)
for i in range(n):
print(” “*(n-i),end=” “,sep=” “)
for j in range(0,i+1):
print(‘{0:6}’.format(a[i][j]),end=” “,sep=” “)
print()

Output:

pascal's triangle

Time complexity: O(n^2)