Pascal triangle program in java

Pascal triangle program in java

Pascal’s triangle is a triangular array of the binomial coefficients.It is named after Blaise Pascal, a famous French Mathematician and Philosopher)

As show in figure,the triangle will start with 1 at the top and placing the numbers below it in the traiangular format.Except the edges(1’s), each number is the sum of two numbers above it.

Algorithm

1.Take ‘number of rows’ from the user(n)
2.Iterate from 0 to n(i)
3.Add spaces for every iteration from n-1 spaces to 0 spaces(j)
4.Iterate from 0 to i(k)
5. Print the values using (number * (i – k) / (k + 1))

Pascal triangle program

package com.answersz.impprograms;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PascalTriangle {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Enter rows for pascal triangle:");

int n = Integer.parseInt(br.readLine());

for (int i = 0; i < n; i++) {
int number = 1;
for (int j = 0; j < n - i; j++) {
System.out.print("   ");
}
for (int k = 0; k <= i; k++) {
System.out.print("   ");
System.out.print(number);
System.out.print("  ");
number = number * (i - k) / (k + 1);
}
System.out.println();

}

} catch (Exception e) {
System.out.println(e);
}
}
}

Output

Chuyên mục

Bài viết mới

GiottoPress by Enrique Chavez