3 ms·
Have you heard about the concept of "loop invariant"? s = 0 i = 0 // Invariant: before and after every iteration, s is equal to sum of [0..i]
by Joker_vD 4y ago
Have you heard about the concept of "loop invariant"?
s = 0
i = 0
// Invariant: before and after every iteration, s is equal to sum of [0..i]
// End condition: i == n
while i != n:
s += i
i += 1
// Here, i == n and so s is a sum of [0..n] because the invariant still holds
That's how loops were supposed to be thought about (and written) since the 70ies, and it's more or less equivalent to induction which is what you're supposed to use when you think about recursive functions.