Section 2.3 More on Proof of Correctness
141
j = a[1]
while i ∙ n do
i = i + 1
if a[i] > j then j = a[i]
end while
//j now has the value of the largest array element
return j
end function ArrayMax
22. Following are four functions intended to return the value a[1] + a[2] + g+ a[n] for n ≥ 1 (the sum of
the first n entries in an array of integers). For those that do not produce correct results, explain what goes
wrong. For those that do produce correct results, do a proof of correctness.
a. ArraySumA (integers n, a[1], a[2], … , a[n])
Local variables:
integers i, j
i = 0
j = 0
while i ≤ n do
i = i + 1
j = j + a[i]
end while
//j now has the value a[1] + a[2] + g+ a[n]
return j
end function ArraySumA
b. ArraySumB (integers n, a[1], a[2], … , a[n])
Local variables:
integers i, j
i = 1
j = 0
while i ≤ n do
j = j + a[i]
i = i + 1
end while
//j now has the value a[1] + a[2] + g+ a[n]
return j
end function ArraySumB
c. ArraySumC (integers n, a[1], a[2], … , a[n])
Local variables:
integers i, j
i = 0
j = 0
while i ≤ n do
j = j + a[i]
i = i + 1
end while
//j now has the value a[1] + a[2] + g+ a[n]
return j
end function ArraySumC
141
j = a[1]
while i ∙ n do
i = i + 1
if a[i] > j then j = a[i]
end while
//j now has the value of the largest array element
return j
end function ArrayMax
22. Following are four functions intended to return the value a[1] + a[2] + g+ a[n] for n ≥ 1 (the sum of
the first n entries in an array of integers). For those that do not produce correct results, explain what goes
wrong. For those that do produce correct results, do a proof of correctness.
a. ArraySumA (integers n, a[1], a[2], … , a[n])
Local variables:
integers i, j
i = 0
j = 0
while i ≤ n do
i = i + 1
j = j + a[i]
end while
//j now has the value a[1] + a[2] + g+ a[n]
return j
end function ArraySumA
b. ArraySumB (integers n, a[1], a[2], … , a[n])
Local variables:
integers i, j
i = 1
j = 0
while i ≤ n do
j = j + a[i]
i = i + 1
end while
//j now has the value a[1] + a[2] + g+ a[n]
return j
end function ArraySumB
c. ArraySumC (integers n, a[1], a[2], … , a[n])
Local variables:
integers i, j
i = 0
j = 0
while i ≤ n do
j = j + a[i]
i = i + 1
end while
//j now has the value a[1] + a[2] + g+ a[n]
return j
end function ArraySumC
