FOR FREE MATERIALS

Diagonal Number pattern

Back to Programming

Description

Diagonal Number pattern:

Here in this pattern printing, the number of lines of the pattern is taken as the input. Two for loops are used to display the pattern. For each line the number of elements is equal to the number of lines of 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 the ith line at the position i the value of i is printed and otherwise 0 is printed.

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=1 to n repeat
			If j=i then
				Print i
			Else
				Print 0
		[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=1;j<=n;j++)--------------------------- n

                                                if(j==i)

                                                                printf("%d ",i);

                                                else

                                                                printf("0 ");

                                printf("\n");

                }

The complexity is: O(n*n)=O(n2)