

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Java program to print Pascal's triangle
Pascal's triangle is one of the classic example taught to engineering students. It has many interpretations. One of the famous one 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 acquire 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.
Algorithm
- Take a number of rows to be printed, n.
- Make outer iteration I for n times to print rows.
- Make inner iteration for J to (N - 1).
- Print single blank space " ".
- Close inner loop.
- Make inner iteration for J to I.
- Print nCr of I and J.
- Close inner loop.
- Print NEWLINE character after each inner iteration.
Example
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
- Related Questions & Answers
- Java Program to Print Star Pascal's Triangle
- C# Program to create Pascal’s Triangle
- Program to generate Pascal's triangle in Python
- Pascal's Triangle in C++
- Pascal's Triangle II in C++
- Java program to generate and print Floyd’s triangle
- Python Program to Print the Pascal's triangle for n number of rows given by the user
- Program to find the nth row of Pascal's Triangle in Python
- How to print integers in the form of Pascal triangle using C?
- Program to print Reverse Floyd’s triangle in C
- Java Program to Print Left Triangle Star Pattern
- Java Program to Print Upper Star Triangle Pattern
- Java Program to Print Downward Triangle Star Pattern
- Finding the elements of nth row of Pascal's triangle in JavaScript
- Java Program to Print the Left Triangle Star Pattern
Advertisements