

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This worksheet provides exercises on writing invariants and assertions to prove the correctness of various algorithms in c, including min function, factorial function, prime number checker, and exponent function.
Typology: Assignments
1 / 2
This page cannot be seen from the preview
Don't miss anything!


Worksheet 4: Assertions and Invariants Name:
In Preparation : Read Chapter 3 to learn more about debugging, testing and proving correctness. In Chapter 3 you learned how assertions and invariants can be used to prove a function or algorithm is correct. In this worksheet you will practice those skills by writing invariants for a number of different algorithms. Write the invariants and assertions that could be used to prove each of the following programs correct. Outside of class in your homework you will develop proofs of correctness by writing the arguments that link each invariant to the next. double min (double [ ] data, int n) { double m = data[0]; assert (n > 0); while (i = 1; i < data.length; i++) { if (data[i] < m) m = data[i]; } return m } int factorial (int n) { int f = 1; assert (n > 0); for (int i = 1; i <= n; i++) { f = f * i; } return f; }
Worksheet 4: Assertions and Invariants Name:
int isPrime (int n) { int i; assert (n > 2); for (i = 2; i * i <= n; i++) { if (0 == n % i) return 0; /* false / } return 1; / true */ } double exp (double a, int n) { double r = 1.0; assert (n >= 0); for (int i = 0; i < n; i++) { r = r * a; } return r; }