Java Tutorials and Program

Khurshid Md Anwar
3 min readMay 19, 2021

Pascal Triangle in java

The pattern similar to Floyed triangle, there is another triangle is called Pascal triangle named after famous French mathematician Blaise Pascal. But it has a little bit different. Here each row is the summation of the left value and a right value of the previous row. if the above row value is missing then it is taken as 0.

The formula is co = co * (i — j + 1) / j Where i is the row number and j is the element position in that row.

Java program for Pascal triangle

import java.util.*;

public class PascalTriangle

{

public static void main(String args[])

{

int rows, co, i, j;

co = 1;

Scanner sc = new Scanner (System.in);

System.out.println(“Enter the number of rows”);

rows = sc.nextInt();

for(i = 0; i < rows; i++)

{

// print the space

for(j = 1; j < rows — i; j++)

{

System.out.print(“ “);

}

// print value

for(j = 0; j <= i; j++)

{

if (j == 0 || i == 0)

{

co = 1;

}

else

{

co = co * (i — j + 1) / j;

}

// row print

System.out.print(co + “ “);

}

System.out.println();

}

} // end of the main() method

} // end of the class

Output

Enter the number of rows

6

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

Java program for Pascal triangle with recursive method

In this program, Pascal triangle is generated with recursive method pascalTriangle(int i, int j).

import java.util.*;

public class PascalTriangleRecursiveMethod

{

//instance variable;

int i, j, k;

public void printRow(int n)

{

for (i = 0; i < n; i++)

{

for (k = 0; k < n — i; k++)

{

// print the space

System.out.print(“ “);

}

for (j = 0; j <= i; j++)

{

System.out.print(pascalTriangle(i, j) + “ “);

}

System.out.println();

}

}

public int pascalTriangle(int i, int j)

{

if (j == 0 || j == i)

{

return 1;

}

else

return pascalTriangle(i — 1, j — 1) + pascalTriangle(i — 1, j);

}

public static void main(String[] args)

{

int rows;

PascalTriangleRecursiveMethod ob = new PascalTriangleRecursiveMethod();

Scanner sc = new Scanner(System.in);

System.out.print(“Enter the number of rows : “);

rows = sc.nextInt();

System.out.println(“Pascal Triangle printed as:”);

System.out.println(“======================”);

ob.printRow(rows);

}

}

Output

Enter the number of rows: 5

Pascal Triangle printed as:

======================

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

More Java programs

Java Program for BinarySearch

Java program for Selection Sort

Loops in Java — Java loop explained with examples

Java for loop

Array in Java

Twin prime number in java

circular prime number program in java

Java program for Pronic Number

Java program for Evil Number

Java Program to find Emirp Number

Neon number program in java

Originally published at https://javaknowhow.blogspot.com.

--

--