FOR FREE YEAR SOLVED

Number Pattern 3

Back to Programming

Description

Number Pattern:

Here in this pattern printing, the number of lines of the pattern is taken as the input. Three for loops are used to display the pattern. The first for loop (the outer for loop) is used to count the line number so the loop is from 1 to n. for each line the elements are printed from i to n and then again from n-1 to i for each line. 

Algorithm

INPUT: the number of lines
OUTPUT: the aforesaid pattern
PROCESS:
Step 1: read n [the number of lines]
Step 2: for i=1 to n repeat
		For j=i to n repeat
			Print j
		[End of ‘for’ loop]
		For k=j-2 to i repeat
			Print k
		[End of ‘for’ loop]
		Move to the next line
	[End of ‘for’ loop]
Step 3: stop.

Code

Time Complexity:

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

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

                                                printf("%d",j);

                                for(k=j-2;k>=i;k--)------------------------------- j-1-i

                                                printf("%d",k);

                                printf("\n");

                }

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