Pascal triangle
Pascal triangle
First we know about the pascal triangle what is this and how we design this triangle in general;
Pascal triangle is the set of numbers arranged in the form of triangle.
Each number in the row is the sum of the left number and right number on the above row. if a number is missing in the above row, it is assumed to be 0. the first row starts with number 1.
Write a program to print the following pattern
Enter the number of row 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Working
Step1- Take number of rows to be printed.
Step2- Make outer iteration from 0 to row times to print row.
Step3- Make inner iteration from o to row-i times to print space in the row.
Step4- Print single black space ” “.
Step5- Close inner loop.
Step6- Make inner iteration from o to i times to print number.
Step7- Apply condition if j or i is 0 so print 1, otherwise calculate c as c=c*(i-j+1)/j.
Step8- Print c.
Step9- Stop.
#include <stdio.h>
int main()
{
int row,c=1,k,i,j;
printf("Enter the number of row ");
scanf("%d",&row);
for(i=0;i<row;i++)
{
for(k=1;k<=row-i;k++)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
if (j==0||i==0)
c=1;
else
c=c*(i-j+1)/j;
printf("%d ",c);
}
printf("\n");
}
return 0;
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//initialize the variable
int row,c=1,k,i,j;
//take user input for number of row
System.out.print("Enter the number of row ");
Scanner sc = new Scanner(System.in);
row = sc.nextInt();
//declare outer loop for every new row.
for(i=0;i<row;i++)
{
//first inner loop for print space.
for(k=1;k<=row-i;k++)
System.out.print(" ");
//Second inner loop for print number in a row
for(j=0;j<=i;j++)
{
//if j or i is 0 so it will print 1
if (j==0||i==0)
c=1;
//we need to perform this calculation
else
c=c*(i-j+1)/j;
System.out.print(" "+c);
}
System.out.println();
}
}
}
import java.util.Scanner;
public class PascalTriangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(“Enter the number of rows for Pascal’s Triangle: “);
int numRows = input.nextInt();
input.close();
for (int i = 0; i < numRows; i++) {
int num = 1;
for (int j = 0; j <= i; j++) {
System.out.print(num + " ");
num = num * (i – j) / (j + 1);
}
System.out.println();
}
}
}