FOR FREE CONTENT

Diamond Number Pattern

Back to Programming

Description

Diamond Number Pattern:

Here the number of lines is taken as input. The number of lines should be odd to print the pattern. The pattern is divided into two halves, in the first half the number of elements are increased and in the 2nd half, the number of elements are decreased. For each half, three for loops are used to print the pattern. 

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<-n/2+1
		Set e<-1
		For i=1 to n/2+1 repeat
			For k=1 to sp repeat
				Print " "
			[End of ‘for’ loop]
			For j=1 to e 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+2
		Set e<-e-2
		For i=n/2+2 to n repeat
			For k=1 to sp repeat
				Print " "
			[End of ‘for’ loop]
			For j=1 to e 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 odd"
[End of ‘if’]
Step 3: Stop.

Code

Time Complexity:

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

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

                                                                printf(" ");

                                                for(j=1;j<=e;j++)------------------------- e

                                                                printf("%d ",j);

                                                printf("\n");

                                                sp--;

                                                e++;

                                }

                                sp+=2;

                                e-=2;

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

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

                                                                printf(" ");

                                                for(j=1;j<=e;j++)--------------------------- e

                                                                printf("%d ",j);

                                                printf("\n");

                                                sp++;

                                                e--;    }

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

Contributed by