Following are four functions intended to return the value a1

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
142 Proofs, Induction, and Number Theory
d. ArraySumD (integers n, a[1], a[2], … , a[n])
Local variables:
integers i, j
i = 1
j = a[1]
while i n do
j = j + a[i + 1]
i = i + 1
end while
//j now has the value a[1] + a[2] + g+ a[n]
return j
end function ArraySumD

Solution

In function ArraySumA, when value of i is equal to n, still it is statisfying while condition so, i = n+1 , therefore j = j + a[n+1]. But there is not any a[n+1] cell.

In function ArraySumC, inital value of i is equal to 0, since i < n which is tatisfying while conition so, j = 0 + a[0], but there is no a[0] cell.

In function ArraySumD, the mistake is similar to function ArraySumA when i is equal to n it is statisfying while condition but there is not any a[n+1] cell.

Function ArraySumB is correct

proof of correctness:
   let assume function is incorrect

   the sum we get from ArraySumB is j which is at end of while loop will be:
           j = 0 + a[1] + a[2] + ... + a[n]
           j = a[1] + a[2] + ... + a[n]

   since our assumption is incorrect

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
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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site