In this article titled "Java Ques 101 - Program to print Pascal's Triangle in Java", we will learn to print a Pascal's Triangle. It is one of the most common pattern-based questions asked by the teachers and the interviewers. Many of us fail to answer such questions, due to a lack of basic knowledge of patterns and Pascal's Triangle.
Java Ques 101 - Program to print Pascal's Triangle in Java
What is Pascal's Triangle?
Pascal's triangle was named after the 17th-century French mathematician Blaise Pascal. Pascal’s triangle is an arrangement of numbers in Triangular form such that it gives the coefficients in the expansion of any binomial expression, such as (x + y)n. The Chinese mathematician Jia Xian introduced a triangular representation for the coefficients. This triangle became popular in the 13th century.
Java Ques 101 - Program to print Pascal's Triangle in Java
Formation of Pascal's Triangle
- Step1: Arrange number 1 along the edges as shown below in fig 1.1.
- Step2: Fill the blank spaces by adding the above digits.
- Step 3: By adding the above two number we get 1+1 = 2. Number 2 will be placed in the third row(white space).
- Step 4: Fill the fourth row, by adding 1+2 in the third row. Place 3 and 3 in the last row.
Java Ques 101 - Program to print Pascal's Triangle in Java
11 11 2 11 3 3 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class demopascal { public static void main(String[] args) { int row=5, i, j, space, number; for(i=0; i<row; i++) { for(space=row; space>i; space--) { System.out.print(" "); } number=1; for(j=0; j<=i; j++) { System.out.print(number+ " "); number = number*(i-j)/(j+1); } System.out.print("\n"); } } } |
Java Ques 101 - Program to print Pascal's Triangle in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> int main() { int rows = 5; int f = 1; int space; int i, j; 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) f = 1; else f = f * (i - j + 1) / j; printf("%4d", f); } printf("\n"); } return 0; } |
Let us see some of the different Pattern questions asked by the teachers and the interviewer-
- Write a program in java to print a star pattern.
- Write a program in java to print a number pattern.
- Write a program in java to print a character pattern.
- How to print * pattern in java?
- How to print * pattern in python
- How to print * pattern in c
- How to print * pattern in java
- How to print * pattern in SQL?
- How to print * pattern in PHP?
- How to print patterns in Python?
- How to print patterns in Java?
- How to print patterns in C?
- How to print patterns in SQL?
- Write a program to print half pyramid of numbers
- Write a program to print inverted half pyramid of *
- Write a program to print full Pyramid of *
- Write a program to print Pascal's triangle
- Write a program to print Floyd's triangle.
No comments:
Post a Comment