FOR FREE CONTENT

Number Pattern 8

Back to Programming

Description

Number Pattern: 

Here to print the pattern the number of lines is taken as input. For each line i the values are printed from i to n and then from i-1 to 1. Three for loops are needed to print the pattern. The first for loop i.e. the outer loop is used to count the number of lines. The two inner for loops are used to print the elements of each line of the pattern.

Algorithm

INPUT: the number of lines
OUTPUT: the aforesaid pattern
PROCESS:
Step 1: read n [number of lines]
Step 2: [printing the pattern]
	For i=1 to n repeat
		For j=i to n repeat
			Print j
		[End of ‘for’ loop]
		For k=i-1 to 1 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=i-1;k>=1;k--)----------------------- i-1

                                                printf("%d ",k);

                                printf("\n");

                }

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