FOR FREE YEAR SOLVED

Number Pattern 9

Back to Programming

Description

Number Pattern:

Here to print the pattern the number of lines is taken as input. The value of n is changed to n+(n-1) because the highest value to be printed is the value equals to n+(n-1). For each line i the values are printed from i to n and then from 1 to i-1. The difference between two consecutive elements is 2. 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]
	Set n<-n+(n-1)
	For i=1 to n (incremented by 2) repeat
		For j=i to n (incremented by 2) repeat
			Print j
		[End of ‘for’ loop]
		For k=1 to i-1 (incremented by 2) 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+=2)--------------------------------------- n/2

                {

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

                                                printf("%d ",j);

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

                                                printf("%d ",k);

                                printf("\n");

                }

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