please explain the logic of question given in lecture:
Given an integer n, print a n*n matrix with square (outermost to
innermost having value n then n-1 .
Nested loops question
Hello Tanu, I hope you tagged the wrong video. And I hope you are asking the question which Bhaiya explained in the video
Python - Loops 2. That is you have given an integer n and you need to print n in the outer portion and then n-1 and so on
So considering this ques :
the code is this
for x in range(n):
for y in range(n):
print(max(x+1,y+1,n-x,n-y), end = " ")
print()
So in this code we are running two loops and both from 0 to n where it means [0,n)
And this line print(max(x+1,y+1,n-x,n-y), end = " ") will print the max no. among x+1,y+1,n-x,n-y
And generally after using print statement we reach to the next line because by default the value of
end = ‘\n’ but here we are specifying it to " " which means we want to print the nos. after one another
and then print() in the next line is to move to the next line
And now if we dry run this :
then take n = 3
here x represents the row no.
here y represents the col no.
both of them are 0 indexed
now pls side by side dry run the code :
for x = 0:
now we have
for y in range(n):
here if y = 0
then max(0+1,0+1,n-0,n-0) which will be equal to n which is 3 in this case
here if y = 1
then max(0+1,1+1,n-0,n-1) which will be equal to 3 in this case
here if y = 2
then max(0+1,2+1,n-0,n-2) which will be equal to 3 in this case
for x = 1:
if we have
y = 0
then max(1+1,0+1,n-1,n-0) which will be equal to n which is 3
if y = 1
then max(1+1,1+1,n-1,n-1) which will be equal to 2
I hope you understand what we have to do in this ques and how it works.
Pls ask in case you feel something confusing or doubtful.
And in case you understand this pls rate well…
Thanks