+ 2

Why do these same codes, output differently?

This is my sum calculator for numbers 1 to N. But for example why when I input "5"; The A code outputs "21" The B code outputs "15" I tried manually their output should be same! Just the line of "while" statements replaced: https://code.sololearn.com/c0ROTx5QW7Hp/?ref=app https://code.sololearn.com/c0yCN5y3091U/?ref=app

10th Aug 2022, 2:51 PM
Amirreza
4 ответов
+ 5
Code A : incrementing i then adding to sum. Next going to check I<=N Code B : adding I to sum then incrementing. (Current incremented value will be added in next iteration). Next going to check I<=N So code B dont adds 6 Code A add 6 to sum as well.. Hope it helps..
10th Aug 2022, 3:08 PM
Jayakrishna 🇮🇳
+ 4
Simple i = 0 sum = 0 i = i + 2 = 2 sum = sum + i = sum + 2 = 0 + 2 = 2 ------------ sum = sum + i = 0 + 0 = 0 i = i + 1 = 2 ---- BTW code is not exactly same
10th Aug 2022, 3:51 PM
A͢J
A͢J - avatar
+ 3
In code A : i is increased before it gets added to sum where as in code B : i is added to sum first then i is increased by 1 , so there is a difference in there outputs
11th Aug 2022, 1:32 AM
Swaraj Soubhagya Khandai
Swaraj Soubhagya Khandai - avatar
+ 3
Jayakrishna🇮🇳 A͢J Swaraj Soubhagya Khandai Thank you all 🙏🌹 I thought the program checks i <= N first of all and stops when i = 5, so no matter i will increase before or after sum cause it has stopped before. But it seems it will check i <= N after doing so.
11th Aug 2022, 3:50 AM
Amirreza