Array ( [0] => [1] => questions [2] => Basic [3] => Square-with-numbers- ) Patterns | Square with numbers | THE INQUISITIVE





Square with numbers

LEVEL:Beginner

Description

Print the pattern as shown below for all test cases.

Input Format

First line contains the value N.

Output Format

Print the output as shown in below examples.


Example 1:

Input
3
Output
1 2 4
3 5 7
6 8 9
Example 2:

Input
4
Output
 1  2  4  7
 3  5  8 11
 6  9 12 14
10 13 15 16
Example 3:

Input
5
Output
 1  2  4  7 11
 3  5  8 12 16
 6  9 13 17 20 
10 14 18 21 23
15 19 22 24 25

oops

Login to see Discussion




Approach


Note: this problem can be divided to two parts
one part initialized half of the array
second part initializes second half of the array

Step-i) create array arr of size N by N
Step-ii) initialize count to 1
Step-iii) assign 0 to i
Step-iv) assign i to j
Step-v) initialize j to 0
Step-vi) assign count to arr[j][temp]
Step-vii) increment count by one and decrement temp by one value
Step-viii) increment j value by one
Step-ix)repeat steps vi to viii till j is less than or equal to i
Step-x)increment i by one value
Step-xi) repeat steps iv to x till i is less than N(now we done with one part of the problem)
Step-xii) assign 1 to i
Step-xiii)assign N-1 to j
Step-xiv)assign i to temp
Step-xv)initialize arr[temp][j] to count
Step-xvi) increment count by one value and decrement j by one value
Step-xvii)increment temp by one value
Step-xviii) repeat steps xv to xvii till temp is less than N
Step-xix) increment i by one value
Step-xx) repeat steps xiii to xix till i is less than N
(by now we have completely intialized the array)
Step-xxi) now by using two loops simply print the array


Time Complexity: O(n^2)
Space Complexity: O(n^2)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution