Social Sciences, asked by angel2163, 1 year ago

What mainataince step says in loop in varient?

Answers

Answered by bunny87901
1
In simple words, a loop invariant is some predicate (condition) that holds for every iteration of the loop. For example, let's look at a simple for loop that looks like this:

int j = 9; for(int i=0; i<10; i++) j--;

In this example it is true (for every iteration) that i + j == 9. A weaker invariant that is also true is that i >= 0 && i < 10 (because this is the continuation condition!) or that j <= 9 && j >= 0.


Loop invariant proofs might seem scary at first, in particular if you are not used to writing mathematical proofs. But they shouldn't be: when you plan to write a loop invariant proof, you already have an algorithm and you have an intuitive notion of why the algorithm is correct. Loop invariant proofs provide you with a very structured way of translating your intuition into something solid.

Let us start with a very simple example. Consider the following computational problem: given an array A (of size n) of numbers, output the sum of the numbers in A. Note that strictly speaking, we will always use a python list instead of an array. Important: Despite the python list being indexed from 0,...,n-1, I will assume that we are using indices from 1,...,n. There are two reasons for this: (a) being consistent with textbook resources you might be using and (b) avoiding a shift (by 1) between the iteration we are arguing about and the corresponding index.


Similar questions