Question

I had a question about loop invariants. I was hoping someone could explain them and give...

I had a question about loop invariants. I was hoping someone could explain them and give a few examples so I can see how they work. Thanks.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

A loop invariant is a formal statement about the relationship between variables in your program which holds true just before the loop is ever run (establishing the invariant) and is true again at the bottom of the loop, each time through the loop (maintaining the invariant).

Here is the general pattern of the use of Loop Invariants in your code:

...
// the Loop Invariant must be true here
while ( TEST CONDITION ) {
// top of the loop
...
// bottom of the loop
// the Loop Invariant must be true here
}
// Termination + Loop Invariant = Goal


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:

Example 1:

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.

There is one thing that many people don't realize right away when dealing with loops and invariants. They get confused between the loop invariant, and the loop conditional ( the condition which controls termination of the loop ).

As people point out, the loop invariant must be true

before the loop starts
before each iteration of the loop
after the loop terminates
( although it can temporarily be false during the body of the loop ). On the other hand the loop conditional must be false after the loop terminates, otherwise the loop would never terminate.

Thus the loop invariant and the loop conditional must be different conditions.
Example 2:

A good example of a complex loop invariant is for binary search.

bsearch(type A[], type a) {
start = 1, end = length(A)

while ( start <= end ) {
mid = floor(start + end / 2)

if ( A[mid] == a ) return mid
if ( A[mid] > a ) end = mid - 1
if ( A[mid] < a ) start = mid + 1

}
return -1

}

So the loop conditional seems pretty straight forward - when start > end the loop terminates. But why is the loop correct? What is the loop invariant which proves it's correctness?

The invariant is the logical statement:

if ( A[mid] == a ) then ( start <= mid <= end )
This statement is a logical tautology - it is always true in the context of the specific loop / algorithm we are trying to prove. And it provides useful information about the correctness of the loop after it terminates.

If we return because we found the element in the array then the statement is clearly true, since if A[mid] == a then a is in the array and mid must be between start and end. And if the loop terminates because start > end then there can be no number such that start <= mid and mid <= end and therefore we know that the statement A[mid] == a must be false. However, as a result the overall logical statement is still true in the null sense. ( In logic the statement if ( false ) then ( something ) is always true. )

Now what about what I said about the loop conditional necessarily being false when the loop terminates? It looks like when the element is found in the array then the loop conditional is true when the loop terminates!? It's actually not, because the implied loop conditional is really while ( A[mid] != a && start <= end ) but we shorten the actual test since the first part is implied. This conditional is clearly false after the loop regardless of how the loop terminates.

Add a comment
Know the answer?
Add Answer to:
I had a question about loop invariants. I was hoping someone could explain them and give...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I was hoping that someone could help me through a discussion/check of a pedigree I had...

    I was hoping that someone could help me through a discussion/check of a pedigree I had to draw for a class project. I am struggling because there are multiple diseases to indicate a mechanism of inheritance for, and I'm getting confused with the instance of two parents affected by two separate diseases. In addition to this, I am supposed to indicate the likelihood of the first child of the last generation inheriting any of these diseases...which I believe I could...

  • Hi! I'm hoping someone can help me with this question. I keep getting the wrong answer...

    Hi! I'm hoping someone can help me with this question. I keep getting the wrong answer when calculating, so I am trying to understand where I am going wrong. Thanks! D 1. For the balanced redox reaction: 3 Mn2+ (aq) + 2Al(s) 3 Mn(s) + 2 A13+ (aq) Calculate Eºcell A. +1.59 V B. +0.93 V C. +0.48 V D. -0.32V E. -0.19 V А B с D E

  • I got stuck on this question about Expected Value, would be great if someone can give...

    I got stuck on this question about Expected Value, would be great if someone can give me a hand. Thanks in advance! Question: Determine all the values a, b such that E((Y - a - bX)^2) is minima. X and Y are real valued random variables.

  • Hello! I am hoping that someone can provide me with an example for this question. I...

    Hello! I am hoping that someone can provide me with an example for this question. I am supposed to write a confidence interval problem (not solve it) using this option-- "Think about a population mean that you may be interested in and propose a confidence interval problem for this parameter. Your data values should be approximately normal. For example, you may want to estimate the population mean number of times that adults go out for dinner each week. Your data...

  • Hey! I have a question about mesh loop analysis in AC RLC circuits. I understand how...

    Hey! I have a question about mesh loop analysis in AC RLC circuits. I understand how to develop the general approach to solving, but there’s a format approach which I don’t understand. (Other than the fact that it’s shorter of course). Can someone explain how the format approach is done?

  • Greetings! I am hoping someone could please tel me if I'm answering this correctly. I think...

    Greetings! I am hoping someone could please tel me if I'm answering this correctly. I think the IV is weather or not the kids had Ritalin or not. I'm also thinking that the DV is the amount of attention kids exhibited. I am not as sure with C. and D., I think C is within and D. is true. Is there a way to easily distinguish weather something is between or within subjects? Thanks! Ritalin has been shown to increase...

  • How do I know if an ion is basic or acidic? Could someone explain how do...

    How do I know if an ion is basic or acidic? Could someone explain how do I determine that? Or is it perhaps a list I need to memorize? Thanks in advance

  • hi i was hoping someone could help me solve this problem, ive been on it for...

    hi i was hoping someone could help me solve this problem, ive been on it for hours and can see to get the answer right Shadee Corp. expects to sell 560 sun visors in May and 360 in June. Each visor sells for $17. Shadee's beginning and ending finished goods inventories for May are 90 and 45 units, respectively. Ending finished goods inventory for June will be 60 units. It expects the following unit sales for the third quarter: Auqust...

  • This was a question on my most recent chemistry exam, I did the best I could...

    This was a question on my most recent chemistry exam, I did the best I could but habw no idea if I did this correctly. No matter what I tried I couldn’t find my answer in the choices but I got close a few times. My professor has a bad habit of rounding numbers so I susspect thay she may have rounded the 80.1°C to 80°C when she was creating the answer choices on the exam. Will someone please work...

  • I had trouble understanding the previous posts to this question, could you explain how after how...

    I had trouble understanding the previous posts to this question, could you explain how after how the answer is gotten as well as the formulas utilized (Voltage/Current laws etc)? Much will appreciated if could be done so. Thanks! 2) In the circuit below, R = 3612, R2 = 4092, R2 = 8092, R = 24092, and E = 120 V w R1 R4 w E R2 WW R3 a) Find the equivalent resistance in the circuit b) Find the current...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT