One aspect of comp science that really lets me down is loop invariants.
A question from a past paper that i cant get is to find the loop invariant of the following segment of code:
bool linearSearchIter(int a[], int n, int target)
{
int i = 0;
bool found = false;
while (i < n && !found)
{
if (a[i] == target)
found = true;
else
i = i + 1;
}
return found;
}
I have found the precondition: a[0...n-1] must be a non empty array, or n >= 1. And the postcondition: Return true if target is true, else false.
Any help would be greatly appreciated! :)