Skip to content

Chapter 15 - Nested Loop Example #37

@petersm3

Description

@petersm3

Don't know if this has already been addressed; logging for completeness

From: Peterson, Matthew
Sent: Tuesday, January 14, 2020 11:07 PM
To: O'Neil, Shawn shawn.oneil@cgrb.oregonstate.edu
Subject: Chapter 15 code question - nested for loop

https://open.oregonstate.education/app/uploads/sites/6/2016/10/II.3_14_nested_loop_illustrated.png

total = 0
sum:int = 0

for i in range(0,4):
    total = total + i
    for j in range(0,3):
        total = total + j + i
        print("total is: " + str(total))
    sum = sum + i

print("Done! Final total is:" + str(total))

What is the line:

sum = sum + i

for, if the variable sum is never referenced? (only the variable 'total' is ever referenced)

Text lists: "We see that both blocks also make use of variables defined outside them; the inner block makes use of sum, i, and j, while lines specific to the outer block make use of sum and i (but not j)."

Referencing your original, hand-written notes, sum is used, (total is never referenced), and the code is different... e.g., there is no line assigning either 'total' or 'sum' to total+i+j OR sum+i+j, respectively.

The below code also produces a different result:

Hand written notes, transcribed:

sum: int = 0
i: int

for i in range(0,4):
    sum = sum + i
    j: int
    for j in range(0,3):
        sum = sum + j
        print("sum is " + str(sum))

    sum = sum + i

print("done")

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions