I need to create a function that returns Pascal's Triangle with n rows, where n is an int argument.
int[][] pascalsTriangle(int n);
A spot has value 1 if it is on the edge of the triangle. Otherwise, it is the sum of the 2 elements above it.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
The Language I need to Use is Java

Respuesta :

A function that returns Pascal's Triangle with n rows:

//import necessary headers

public class Pascal_Triangle {

   // calculate factorial  

   static int factorial(int n)

   {

       int fact = 1;

       int i;

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

       {

           fact*=i;

       }

       return i;

   }

   // Actual code to display the //pascal triangle

   static void display(int n)  

   {

       int i;

       int line;

       for(line=1;line<=n;line++)

       {

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

           {

               System.out.print((factorial(line)/factorial(line-i) * factorial(i)) + " ");

           }

           System.out.println();

       }

   }

   // To read user input

   public static void main(String[] args){  

       BufferedReader breader=new BufferedReader(new InputStreamReader(System.in));

       int n;

       System.out.println("Enter the size for creating Pascal triangle");

       try {

           n = Integer.parseInt(breader.readLine());

       }

       catch(Exception e){

           System.out.println("Please enter a valid Input");

           return;

       }

       System.out.println("The Pascal's Triangle is");

       display(n);

   }

}