Homework: the fraction
The folder hw/05 holds three files you fill in and one you don't change.
The functions: hw/05/numbers.c
The file numbers.h already lists three function prototypes with their contracts. You don't need to change it: topic 7 explains how .h files work. You write the function bodies in numbers.c:
int gcd(int a, int b): the greatest common divisor, recursively (Euclid's algorithm):gcd(a, 0) = a, otherwisegcd(a, b) = gcd(b, a % b). E.g.gcd(84, 36) = 12.int digit_sum(int n): the digit sum, recursively, as in the topic.digit_sum(472) = 13.int is_prime(int n): 1 ifnis prime, otherwise 0. 0 and 1 are not prime. No recursion needed here: a loop is enough.
Each function checks its precondition with an assert on its first line, as written in numbers.h.
The fraction: hw/05/main.c
The program asks for the numerator and the denominator, prints the simplified fraction and, when it is more than 1, the mixed number. gcd helps with simplifying: divide both the numerator and the denominator by their greatest common divisor.
Numerator: 84
Denominator: 36
84/36 = 7/3
Mixed number: 2 1/3
The numerator must be non-negative, the denominator positive. Ask again after an invalid value:
Numerator: -5
Numerator must not be negative.
Numerator: 5
Denominator: 0
Denominator must be positive.
Denominator: 9
5/9 = 5/9
If the denominator is 1 after simplifying, print only the whole number: 48/12 = 4.
Input goes only through read_int from input.h.
Tests
Six tests:
hw05_functions:asserts that check your three functions (hw/05/unit_tests.c);hw05_precondition:gcd(-1, 5)must stop at yourassertinstead of returning something;hw05_fraction_1…3: the program's output with three inputs (hw/05/tests/);hw05_contracts:numbers.chas anassert(and noTODOleft.
ctest --preset debug -L hw05
While the functions aren't written, the first two tests end like this:
Start 11: hw05_functions
1/6 Test #11: hw05_functions ...................***Failed 0.04 sec
Assertion failed: gcd(84, 36) == 12, file C:/.../hw/05/unit_tests.c, line 14
Start 12: hw05_precondition
2/6 Test #12: hw05_precondition ................***Failed 0.08 sec
=== hw05_precondition: FAILED ===
The program did not stop, but it should have.
gcd(-1, 5) must stop at an assert that checks the precondition a >= 0.
--- output ---
gcd(-1, 5) returned 0: no assert stopped it.
unit_tests.c stops at the first assert that fails. Open it at line 14: you'll see which case it checks and which ones are still waiting.
Start with numbers.c: while gcd doesn't work, the fraction tests won't pass either.
Handing in
Commit and push. Actions → Points: HW 5 (Fraction), 10 points when all six tests pass.