CS FundamentalsHardGATE CS

This loop sums an array:

This loop sums an array:
i = 0; s = 0
while i < n:
    s = s + a[i]
    i = i + 1
Which assertion is a loop invariant (true every time the condition i < n is tested) that, with the exit condition, proves s is the sum of all n elements?
  1. A. s = a[0] + … + a[i] and 0 ≤ i < n
  2. B. s = a[0] + … + a[i − 1] and 0 ≤ i ≤ n
  3. C. s = a[0] + … + a[n − 1]
  4. D. i < n

Correct answer: B. s = a[0] + … + a[i − 1] and 0 ≤ i ≤ n

Initially i = 0 and the empty sum is 0; each iteration adds a[i] and then increments i, so s always holds the first i elements and 0 ≤ i ≤ n. At exit i = n, giving the full sum. Including a[i] is off by one, and i < n is false on exit.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic