FOR FREE YEAR SOLVED

Full Star Pyramid

Back to Programming

Description

Full Star Pyramid

      *

    ***

  *****

*******

To print this pattern, the number of lines is taken as the input from user. Three for loops (one outer for loop and two inner for loops) are used here to print the pattern. The outer for loop is used to count the line number. For ith line the number of spaces before printing the star is n-i. so the first inner for loop used to print the spaces executes from 1 to n-i for each line i. the number of stars are increasing by 2 at each line. so, a separate variable is used to count the number of stars for a line. so, the 2nd inner for loop is used to print the star of each line.

Algorithm

INPUT: number of lines
OUTPUT: the aforesaid pattern
PROCESS:
Step 1: [taking the input]
	Read n [number of lines]
Step 2: [printing the pattern]
	Set st<-1
For i=1 to n repeat
		For j=1 to n-i repeat
			Print " "
		[End of ‘for’ loop]
		For k=1 to st repeat
			Print “*"
		[End of ‘for’ loop]
		Move to the next line
		Set st=st+2
	[End of ‘for’ loop]
Step 3: Stop

Code

Time Complexity:

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

                {               //printing the spaces

                                for(j=1;j<=n-i;j++)-----------------------------------------------------O(n-i)

                                                printf(" ");

                                //printing the stars

                                for(k=1;k<=st;k++)----------------------------------------------------O(st)

                                                printf("*");

                                printf("\n");

                                st+=2;     }

The first ‘for’ loop is running from 1 to n and the inner for loop is running from 1 to n-i and the second loop is from 1 to st. so the time complexity is O(n*(n-i+st))=O(n2).