I was going over some problems for my discrete math class, and read an exercise that caught my attention (note: this is not homework. I’m just purely curious).
Question: How many times is the “print” statement executed for the following program segment? (i, j, k, m are integers):
for i := 1 to 20 do
for j := 1 to i do
for k := 1 to j do
for m := 1 to k do
print (i * j) + (k * m)
I tried to do it in python, but it was boring because I got it done in a few seconds. So for fun I tried to do it with DrRacket using scheme as the language. However, after reading documentation on loops, I can’t seem to find reference for loops of this kind. So, using this specific example (or I guess a general one with an indefinite number of loops), how can this problem be solved?
A loop like this:
Is equivalent to this in Racket, assuming that a loop range that looks like this:
1 to 20includes all the numbers from 1 up to (and including) 20.Notice that the above is not limited to one nested loop, you can declare as many nested loops and iteration variables as needed.