Control Flow
Loop Invariant
A loop invariant is a fact that stays meaningful before and after each iteration.
Loop Invariant
loop_invariant.c
#include <stdio.h>
int main(void) {
int limit = ;
int total = 0;
int processed = 0;
while (processed < limit) {
processed++;
total += processed;
}
printf("processed=%d\n", processed);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int limit = ;
int total = 0;
int processed = 0;
while (processed < limit) {
processed++;
total += processed;
}
printf("processed=%d\n", processed);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int limit = ;
int total = 0;
int processed = 0;
while (processed < limit) {
processed++;
total += processed;
}
printf("processed=%d\n", processed);
printf("total=%d\n", total);
return 0;
}
invariant
`total` is always the sum of the values processed so far.
processed count
`processed` records how many values have contributed to the invariant.