2

I don't understand this problem

Why counter can be equal to 1 i=1 (like in the code below) or can be replaced by i = 0 and the result is the same?

n = 4
sum = 0  # initialize sum
i = 1  # initialize counter
while i <= n:
    sum = sum + i
    i = i+1  # update counter
print("The sum is", sum)
5
  • 7
    The extra iteration with i=0 doesn't add anything to sum. Commented Dec 13, 2017 at 7:12
  • 1
    You can get a clearer idea by running the code step by step from Python Tutor Commented Dec 13, 2017 at 7:19
  • why i = 0 and not i = 1 if the result is the same after I run the code? Commented Dec 13, 2017 at 7:23
  • sum + 0 = sum. Adding 0 does not change the result. Commented Dec 13, 2017 at 7:38
  • I am very good at math. :) thank you Luk Commented Dec 13, 2017 at 8:08

1 Answer 1

1
# with added line numbers

1. while i < n: # modified this for simplicity.
2.     sum = sum + i
3.     i = i+1    # update counter
4. print("The sum is", sum)

Here is the execution to wrap your head around it.

# L1: i=1 n=4 sum=0
# L2: i=1 n=4 sum=1
# L3: i=2 n=4 sum=1
# L1: check i<n - True, 2 is less than 4
# L2: i=2 n=4 sum=3
# L3: i=3 n=4 sum=3
# L1: check i<n - True, 3 is less than 4
# L2: i=3 n=4 sum=6
# L3: i=4 n=4 sum=6
# L1: check i<n - False, 4 not less than 4 ; its equal. condition fail.
# L4: print 6

In case of starting from 0.

# L1: i=0 n=4 sum=0
# L2: i=0 n=4 sum=0 # see sum is 0+0
# L3: i=1 n=4 sum=0

# L1: check i<n - True, 1 is less than 4
# L2: i=1 n=4 sum=1
# L3: i=2 n=4 sum=1
# L1: check i<n - True, 2 is less than 4
# L2: i=2 n=4 sum=3
# L3: i=3 n=4 sum=3
# L1: check i<n - True, 3 is less than 4
# L2: i=3 n=4 sum=6
# L3: i=4 n=4 sum=6
# L1: check i<n - False, 4 not less than 4 ; its equal. condition fail.
# L4: print 6

When you contrast both; you did an extra iteration of work in the second case. But, that contributes nothing to the sum.

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.