Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints the first n lines of Pascal’s triangle. Following are the first 6 rows of Pascal’s Triangle.In this article, we will look into the process of printing Pascal’s triangle. Pascal’s triangle is a pattern of the triangle which is based on nCr.below is the pictorial representation of Pascal’s triangle.

Illustration:
Input : N = 5
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Methods:
There are two approaches for the same. Let’s check them out.
- Using nCr formula
- Using Binomial Coefficient
Method 1: Using nCr formula
Implementation: Follow the below algorithm for printing Pascal’s triangle using the nCr formula
- Let n be the number of rows to be printed
- Use outer iteration a from 0 to k times to print the rows
- Make inner iteration for b from 0 to (K – 1).
- Then print space as ” “.
- Close the inner ‘b’ loop.
- Make inner iteration for b from ‘0’ to ‘a’.
- Output nCr of ‘a’ and ‘b’.
- Close inner loop.
- Print newline character (\n) after each inner iteration.
Example
Java
import java.io.*;
public class GFG {
public int factorial( int a)
{
if (a == 0 )
return 1 ;
return a * factorial(a - 1 );
}
public static void main(String[] args)
{
int k = 4 ;
int a, b;
GFG g = new GFG();
for (a = 0 ; a <= k; a++) {
for (b = 0 ; b <= k - a; b++) {
System.out.print( " " );
}
for (b = 0 ; b <= a; b++) {
System.out.print(
" "
+ g.factorial(a)
/ (g.factorial(a - b)
* g.factorial(b)));
}
System.out.println();
}
}
}
|
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Time complexity: O(2n) due to recursive method
Auxiliary Space: O(n) due to recursive stack space
Method 2: Using Binomial Coefficient
The ‘A’th entry in a line number line is Binomial Coefficient C(line, a) and all lines start with value 1. The idea is to calculate C(line, a) using C(line, a-1).
C(line, i) = C(line, i-1) * (line - i + 1) / i
Implementation:
Example
Java
import java.io.*;
public class GFG {
public static void printPascal( int k)
{
for ( int line = 1 ; line <= k; line++) {
for ( int b = 0 ; b <= k - line; b++) {
System.out.print( " " );
}
int C = 1 ;
for ( int a = 1 ; a <= line; a++) {
System.out.print(C + " " );
C = C * (line - a) / a;
}
System.out.println();
}
}
public static void main(String[] args)
{
int n = 6 ;
printPascal(n);
}
}
|
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Time complexity: O(n^2) where n is given input for no of rows of pascal triangle
Auxiliary Space: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Sep, 2022
Like Article
Save Article