Jul-31-2021, 02:11 PM
(Jul-31-2021, 01:41 PM)deanhystad Wrote: You are using the wrong term. Your program has two loops. The outer loop ITERATES 4 times: (0, 1, 2, 3). The inner loop iterates 16 times: 4x(0, 1, 2, 3). Some would also say (correctly) that the inner loop ITERATES 4 times and this is repeated 4 times.
Add a print statement to the loop:
x = 0 n = 5 for i in range(1, n): for j in range(1, n): if((i+j) == 2): x = x + 2 if((i+j) == 3): x = x + 3 if((i+j) == 4): x = x + 4 v print(x)Focusing on the last two columns you can see that the value of the last column (x) only changes when the value in the 3rd column (i+j) is 2, 3 or 4.
Output:1 1 2 2 <- Three changes while i = 1 1 2 3 5 <- 1 3 4 9 <- 1 4 5 9 2 1 3 12 <- Two changes while i = 2 2 2 4 16 <- 2 3 5 16 2 4 6 16 3 1 4 20 <- Only one change while i = 3 3 2 5 20 3 3 6 20 3 4 7 20 4 1 5 20 <- No changes while i = 4 4 2 6 20 4 3 7 20 4 4 8 20
I would explain this as "x only increases if the value of i+j is 2, 3 or 4", but if you wanted to describe it using loops you could say:
When i is 1 you add values for j = 1, 2 and 3 (2, 3, 4)
When i is 2 you add values for j = 1 and 2 (3, 4)
When i is 3 you add values for j = 1 (4)
When i is 4 you don't add any values
x = 2 + 2*3 + 3*4 = 2 + 6 + 12 = 20
Thank you for your reply.
I understood with your statement
print(i, j, i+j, x),
this output make me clear.
This "x = 2 + 2*3 + 3*4 = 2 + 6 + 12 = 20" calculation I can't understand.
But it's okay, I really appreciate to your statement, let me know how this statement work.
Thanks