Note 6.5.1.
What would happen if we put the assignment
runningTotal = 0
inside the for statement? Not sure? Try it and find out.runningtotal
starts out with a value of 0. Next, the iteration is performed x
times. Inside the for loop, the update occurs. runningtotal
is reassigned a new value which is the old value plus the value of x
.runningTotal = 0
inside the for statement? Not sure? Try it and find out.initialize the accumulator variable
repeat:
modify the accumulator variable
# when the loop terminates the accumulator has the correct value
def square(x):
for counter in range(x):
runningtotal = 0
runningtotal = runningtotal + x
return runningtotal
toSquare
in line 9 to -10
and run.toSquare
in line 9 back to 10
and run.runningtotal = runningtotal + x
to use multiplication instead of addition? Make this change to the program and look at the output.additive identity
and multiplicative identity
. Properly initialize the accumulator variable and run the program.x
. It is also important that the loop repeat the proper number of times. How many times do we need to execute line 5 to get the square of x
? Change line 4 to repeat the correct number of times. Now the program should produce the correct result.toSquare
in line 9 to -10
and run. Now negative inputs also work!toSquare
also.