Wednesday 10 December 2014

Number Pattern in C# - 15 (Pascal Triangle)

Ques: Write a program to print PASCAL triangle



In pascal triangle we start with print "1" at the top, and after that continue placing numbers below it in the for pyramid triangle. Each number in this triangle is the sum of above two number starting from left.

Suppose we have to print this pascal triangle
    
      1                        
      1  1                      
    1  2  1                     
  1  3  3  1           
1  4  6  4  1                

ROW 0 = 1;
ROW 1 = ( 0 + 1);
ROW 2 = ( 0 + 1)( 1 + 0);
ROW 3 = ( 0 + 1 )( 1 + 2 )( 2 + 1 )( 1 + 0 );
ROW 4 = ( 0 + 1 )( 1 + 3 )( 3 + 3 )( 3 + 1 )( 1 + 0 );


There are lots of way to create Pascal Triangle Two of them are here

Source Code 1:

  1. using System;  
  2. public class PascleTriangle  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         int row,i,j,c;  
  7.         Console.Write("Enter the no. of row you want to print: ");  
  8.         row=Convert.ToInt32(Console.ReadLine());  
  9.     
  10.         for(i=0;i<=row;i++)  
  11.         {  
  12.             c=1;  
  13.             for(j=i;  j<=row-1; j++)  
  14.             Console.Write(" ");  
  15.           
  16.             for(j=0;j<=i;j++)  
  17.             {  
  18.                 Console.Write("{0} ",c);  
  19.                 c=(c*(i-j)/(j+1));  
  20.             }  
  21.             Console.WriteLine();      
  22.         }  
  23.         Console.ReadLine();  
  24.     }  
  25. }

OR

Source Code 2:

  1. using System;  
  2. public class PascleTriangle  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         int i,j,row,pas;  
  7.           
  8.         Console.Write("Enter the no. of rows in pascle Triangle: ");  
  9.         row=Convert.ToInt32(Console.ReadLine());  
  10.   
  11.         for(i=0; i<=row;i++)  
  12.         {  
  13.             for(j=0;j<=(row-i);j++)  
  14.             Console.Write(" ");  
  15.   
  16.             for(j=0; j<=i; j++)  
  17.             {  
  18.                 pas=calc(i)/(calc(j)*calc(i-j));  
  19.                 Console.Write("{0} ",pas);  
  20.             }  
  21.             Console.WriteLine();  
  22.         }  
  23.         Console.ReadLine();  
  24.     }  
  25.   
  26.     public int calc(int num)  
  27.     {  
  28.         int x, res=1;  
  29.         for(x=1;x<=num;x++)  
  30.         res=res*x;  
  31.         return res;  
  32.     }  
  33. }  

  
Screen Shot of Pascal triangle
Fig: Screenshot of Output