CREATE OWN LIBRARY

Pascal's Triangle

Back to Programming

Description

Pascal's Triangle

The aforesaid pattern is known to us as Pascal’s triangle. In mathematics, it represents a triangle of binomial co-efficients. It is named after the mathematician Blaise Pascal. Here to print the pattern the number of lines is taken as inputs. The first for loop is used to count the number of lines. The first inner for loop is used to print the spaces before the elements of each line. the second for loop is used to print the elements. For each line, the elements are started from 1. The next element is the sum of the first two elements of the previous line, the next element is the sum of the 2nd and 3rd elements of the previous line, and so on.

Algorithm

INPUT: number of lines
OUTPUT: the aforesaid pattern
PROCESS:
Step 1: read n [Taking the input]
Step 2: [Printing the pattern]
	Set c<-1
	for  i=0 to n-1 repeat
        		for sp=1 to n-i repeat
            			print "  "
        		for  j=0 to i repeat
            			if  j=0 or i=0 then
                			Set c <- 1
            			else
                			Set c<-c×(i-j+1)/j
            			[End of ‘if’]
Print  c
        		[End of ‘for’ loop]
        		Move to the next line
    	[End of ‘for’ loop]
Step 3: Stop.

Code

Time Complexity:

    for (i=0; i<n; i++)-------------------------------------

   {

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

           printf("  ");

        for (j=0; j<=i; j++)----------------------------------- i

        {

           if (j==0 || i==0)

               c = 1;

           else

               c=c*(i-j+1)/j;

           printf("%d   ", c);

        }

       printf("\n");     }

 

The complexity is: O(n*(n-i+i))=O(n2)