Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Program to print pascal's triangle using a 2D array in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.05k
    Comment on it

    Pascal's Triangle:

     

    Program to print Pascal's triangle:

    import java.io.*;
    public class Pascal{
    
         public static void main(String []args)throws IOException{
    
           InputStreamReader isr=new InputStreamReader(System.in);
           BufferedReader br=new BufferedReader(isr);
           System.out.println("Enter the no. of rows");
           int n=Integer.parseInt(br.readLine());
    
           int a[][]=new int[50][50];
           
           int i=0,j=0,sp=n-1;
           
           for(i=0;i<n;i++)
           {
               a[i][i]=a[i][0]=1; // to assign value 1 to the diagonals
           }
           for(i=0;i<n;i++)
           {
               for(j=1;j<i;j++)
               {
                   a[i][j]=a[i-1][j-1]+a[i-1][j];
               }
           }
           for(i=0;i<n;i++)
           {
               for(j=0;j<sp;j++) // loop for printing the spaces
               {
                   System.out.print(" ");
               }
               for(j=0;j<=i;j++)
               {
                   System.out.print(a[i][j]+" ");
               }
               System.out.println();
               sp--;
           }
           
           
         }
    }
    

     

    This way we can print the pascal's triangle using 2D array correctly because it is often confused by multiple of 11 which is not a correct method and it will not support after 5 rows.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: