
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Pascal's Triangle in Java
In this article we will learn to print Pascal's triangle in Java. Pascal's triangle is one of the classic examples taught to engineering students. It has many interpretations. One of the famous ones is its use with binomial equations.
All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquires a space in Pascal's triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0). The output is sandwiched between two zeroes. The process continues till the required level is achieved.
Problem Statement
Write a program in Java to print Pascal's triangle.
Input
n=4
Output

Steps to print Pascal's triangle
Following are the steps to print Pascal's triangle ?
- Take a number of rows to be printed, n.
- Make outer iteration i for n times to print rows using for loop.
- Make inner iteration for j to (n - 1).
- Print a single blank space " " and close the inner loop.
- Make inner iteration for j to i.
- Print nCr of i and j and then close the inner loop.
- Print NEWLINE character after each inner iteration.
Java program to print Pascal's triangle
Below is the Java program to print Pascal's triangle ?
public class PascalsTriangle { static int factorial(int n) { int f; for(f = 1; n > 1; n--) { f *= n; } return f; } static int ncr(int n,int r) { return factorial(n) / ( factorial(n-r) * factorial(r) ); } public static void main(String args[]) { System.out.println(); int n, i, j; n = 5; for(i = 0; i <= n; i++) { for(j = 0; j <= n-i; j++) { System.out.print(" "); } for(j = 0; j <= i; j++) { System.out.print(" "+ncr(i, j)); } System.out.println(); } } }
Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
Code Explanation
This Java program prints Pascal's Triangle, where each number is the sum of the two numbers above it. It starts by defining a factorial() method to calculate a number's factorial. The ncr method then uses this to compute combinations for the triangle.
In the main() method, the number of rows is set to 5, and i and j are initialized for iteration. An outer loop iterates through each row. Within this loop, spaces are printed for formatting, and then the triangle values are printed using the ncr method. After each row, the program moves to the next line.