Lab 03 - Assert
Thanks for my Lab Tutor Zhang Puyu!
Slides:
Exercise 1 Review
Code Style
Initialize the variable immediately after the declaration.
For example,
// Not Recommended
double num;
num = cs1010_read_double();
// Recommended
double num = cs1010_read_double();Do not declare the function and then implement it somewhere else (Usually after
main()). Implement your function right after the declaration.
No return after else
Code Example
Out of succient reasons, the else is of no use. So, we can simplify the code to below
No nested If
If your code is like below
Since there is only one if statement inside the "outer" if, so there is no need to use the nested if. And we can simplify it into
Assert Library
assert.h is a library designed to help with debugging procedures.
Usage
assert(p) where p is a boolean expression. When the condition p fails during program execution, the program will halt with an error message.
Exercise 1 Further Discussion
odd.c
A solution that uses no condition is that , where is the smallest odd number that is strictly bigger than .
The Deriving process

multiple.c
Modulo is not defined when we divide a non-zero number by 0. That is , where , is not defined!!!
date.c
There is a method not using conditions. Map each date to the integer .
power.c
Ways to optimize
Remove the useless work, when the base is 0, -1 or 1.
Half the calculation
Recall that
Then convert it to code will be intuitive
taxi.c
A normal way to compute ceil()
A smart way to compute ceil()
Suppose we want to calculate , where and are two possitive integers. First, let us write , where and . Now, let's consider
If , then we will get as the output. If , then the above numerator is at least but strictly less than , so the quotient evaluates to , which will be our output.
Thus, convert the result into `C` code ```c long ceil_of_quotient(long n, long m) { return (n + m - 1) / m; } ```
Last updated