FOR FREE YEAR SOLVED

Sandglass Number Pattern

Back to Programming

Description

Sandglass Number Pattern:

Here the number of lines is taken as input. The number of lines should be even to print the pattern. The pattern is divided into two halves, in the first half the numbers of elements are decreased and in the 2nd half the numbers of elements are increased.

Algorithm

INPUT: number of lines
OUTPUT: the aforesaid pattern
PROCESS:
Step 1: read n [the number of lines]
Step 2: if n mod 2=0 then
		Set sp<-0
		Set e<-1
		For i=1 to n/2 repeat
			For k=1 to sp repeat
				Print " "
			[End of ‘for’ loop]
			For j=e to n/2 repeat
				Print j
			[End of ‘for’ loop]
			Move to the next line
			Set sp<-sp+1
			Set e<-e+1
		[End of ‘for’ loop]
		Set sp<-sp-1
		Set e<-e-1
		For i=n/2+1 to n repeat
			For k=1 to sp repeat
				Print " "
			[End of ‘for’ loop]
			For j=e to n/2 repeat
				Print j
			[End of ‘for’ loop]
			Move to the next line
			Set sp<-sp-1
			Set e<-e-1
		[End of ‘for’ loop]
	else
		print “The number of lines should be even"
[End of ‘if’]
Step 3: Stop.

Code

Time Complexity:

for(i=1;i<=n/2;i++)------------------------------------------------------------- n/2

                                {              for(k=1;k<=sp;k++)---------------------- sp

                                                                printf(" ");

                                                for(j=e;j<=n/2;j++)----------------------- n/2-e+1

                                                                printf("%d ",j);

                                                printf("\n");

                                                sp++;

                                                e++;

                                }

                                sp-=1;

                                e-=1;

                                for(i=n/2+1;i<=n;i++)---------------------------------  n/2

                                {              for(k=1;k<=sp;k++)------------------------ sp

                                                                printf(" ");

                                                for(j=e;j<=n/2;j++)-------------------------- n/2-e+1

                                                                printf("%d ",j);

                                                printf("\n");

                                                sp--;

                                                e--;

                                }

The complexity is: O(2*((n/2)*(sp+n/2-e+1)))=O(n2)

Contributed by