FOR FREE YEAR SOLVED

Number Pattern 19

Back to Programming

Description

Number Pattern: 

For printing the aforesaid pattern, the number of lines is taken as input. For the odd lines the values are printed in ascending order and for the even lines the values are printed in descending order.

Algorithm

INPUT: Number of lines
OUTPUT: the aforesaid pattern
PROCESS:
Step 1: [taking the input]
	Read n [number of lines]
Step 2: [printing the pattern]
	Set p<-1
	For i=1 to n repeat
		For k=1 to n-i repeat
			Print “ “
		[End of ‘for’ loop]
		If i mod 2≠0 then
			For j=1 to i repeat
				Print p
				Set p<-p+1
			[End of ‘for’ loop]
		else
			Set p<-(p+i)-1
			For j=1 to i repeat
				Print p
				Set p<-p-1	
			[End of ‘for’ loop]
			Set p<-p+i+1
		[End of if]
		Move to the next line
	[End of ‘for’ loop]
Step 3: Stop.

Code

Time Complexity:

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

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

                                                printf(" ");

                                if(i%2!=0)

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

                                                {              printf("%d ",p);

                                                                p++;  }

                                }

                                else

                                {              p=(p+i)-1;

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

                                                {

                                                                printf("%d ",p);

                                                                p--;   }

                                                p=p+i+1;   }

                                printf("\n");

                }

 

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