PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#Prints a square matrix of numbers counting from 1 to N*N, N being user given input, in a diagonal fashion.
def fillMatrix(i, count, matrix, size):
if i < size:
for x in range(0, i+1):
matrix[x][size-(i+1)+x] = count
count += 1
else:
for x in range(i-size+1, size):
matrix[x][x-(i-size)-1] = count
count += 1
return count
try:
size = int(input("Enter the size of the matrix: "))
except ValueError:
print("\n\nInvalid input.")
matrix = [[0 for x in range(0, size)] for y in range(0, size)]
count = 1
for i in range(0, size+(size-1)):
count = fillMatrix(i, count, matrix, size)
print("\n")
row = 0
while row < len(matrix):
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run