Computer programming - Lab 1
Homework
1. Write a function that returns the median of three numbers (i.e., the
middle one, when ordering the numbers by value).
Use conditional expressions. Avoid long and complex code.
Test your code for all possible orderings of the arguments (how many?)
Hint: if you first compare two numbers, you are left with a similar
problem but with extra information: the ordering between two of the numbers.
Write a function to solve this subproblem, and call it in the function
that you were asked to write.
2. A really inefficient way of computing Fibonacci numbers is by using
the recurrence directly as given: F0 = 0,
F1 = 1, Fn = Fn-1 + Fn-2.
Figure out how many calls are needed to compute Fn. Confirm
by writing a program that also prints something in the function.
3. A nonnegative decimal number (i.e., in base 10) can be viewed recursively
as either a single digit, or a number followed by a digit (we single out
the last digit rather than the first since the two parts are computable as quotient and remainder modulo 10).
Write a recursive function that returns the first (most significant) digit of a number when written in base 10.
Compiling your program
Compiling and running are two distinct steps.
The compiler converts the source file (.c) to an executable file.
Command: gcc options file.c
You should use these options (in any order)
- -Wall produce all types of warning messages. Your code should compile with no warnings (certainly without any warnings that you are absolutely sure don't matter).
- -O optimize. In the process, will warn about uninitialized variables. If your reason is to optimize, look up different variants.
- -std=c11 Use the latest standard (2011). Useful e.g. for local declarations in for. For older compilers, use -std=c99 .
- -lm Compile with the math library. Needed when you use functions from math.h
- -o execfile Use if you don't want the default name a.out for the generated executable.
To run your program, use the command
./a.out
where . (dot) means the current directory (where you compiled),
a.out is the executable file name (replace as needed) and /
is the directory separator character under Linux.
Marius Minea
Last modified: Wed Sep 28 18:20:00 EEST 2016