Assertions and Invariants Worksheet for Data Structures in C, Assignments of Data Structures and Algorithms

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

Pre 2010

Uploaded on 08/30/2009

koofers-user-epy-1
koofers-user-epy-1 🇺🇸

5

(1)

10 documents

1 / 2

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Worksheet 4: Assertions and Invariants Name:
An Active Learning approach to Data Structures using C
1
Worksheet 4: Assertions and Invariants
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;
}
pf2

Partial preview of the text

Download Assertions and Invariants Worksheet for Data Structures in C and more Assignments Data Structures and Algorithms in PDF only on Docsity!

Worksheet 4: Assertions and Invariants Name:

An Active Learning approach to Data Structures using C 1

Worksheet 4: Assertions and Invariants

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:

An Active Learning approach to Data Structures using C 2

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; }