Java program to display Pascal triangle
Pascal triangle in java:
Program:
import java.util.Scanner;
public class Pascal_triangle
{
public static void main(String[] args)
{
int i,j,k;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int n = sc.nextInt();
int c[][] = new int[n][n];
int space = (n-1);
for(i=0;i<n;i++)
{
for(k=0;k<space;k++)
{
System.out.print(" ");
}
for(j=0;j<i;j++)
{
if(i==j)
{
c[i][j] = 1;
System.out.print(c[i][j] + " ");
}
else if(j==0)
{
c[i][j] = 1;
System.out.print(c[i][j] + " ");
}
else
{
c[i][j] = c[i-1][j-1] + c[i-1][j];
System.out.print(c[i][j] + " ");
}
}
System.out.println();
space--;
}
}
}
Output:
Enter number of rows: 7
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
"If you have any other logic to attain the same result please email the code to sharkrish50@gmail.com"
![]() |
Pascal triangle |
Program:
import java.util.Scanner;
public class Pascal_triangle
{
public static void main(String[] args)
{
int i,j,k;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int n = sc.nextInt();
int c[][] = new int[n][n];
int space = (n-1);
for(i=0;i<n;i++)
{
for(k=0;k<space;k++)
{
System.out.print(" ");
}
for(j=0;j<i;j++)
{
if(i==j)
{
c[i][j] = 1;
System.out.print(c[i][j] + " ");
}
else if(j==0)
{
c[i][j] = 1;
System.out.print(c[i][j] + " ");
}
else
{
c[i][j] = c[i-1][j-1] + c[i-1][j];
System.out.print(c[i][j] + " ");
}
}
System.out.println();
space--;
}
}
}
Output:
Enter number of rows: 7
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
"If you have any other logic to attain the same result please email the code to sharkrish50@gmail.com"
Comments
Post a Comment