About GBdirect Consultancy Training Development

Section navigation

Leeds Office (National HQ)

GBdirect Ltd
Leeds Innovation Centre
103 Clarendon Road
West Yorkshire
United Kingdom


tel: +44 (0)870 200 7273
Sales: 0800 651 0338

South East Regional Office

GBdirect Ltd
18 Lynn Rd
United Kingdom


tel: +44 (0)870 200 7273
Sales: 0800 651 0338

Please note: Initial enquiries should always be directed to our UK national office in Leeds (West Yorkshire), even if the enquiry concerns services delivered in London or South/East England. Clients in London and the South East will typically be handled by staff working in the London or Cambridge areas.

4.6. Exercises

If you skipped the section on Linkage, then Exercise 4.2, Exercise 4.3, and Exercise 4.4 will cause you problems; it's up to you whether or not you want to read it and then try them.

Write a function and the appropriate declaration for the following tasks:

Exercise 4.1. A function called abs_val that returns int and takes an int argument. It returns the absolute value of its argument, by negating it if it is negative.

Exercise 4.2. A function called output that takes a single character argument and sends it to the program output with putchar. It will remember the current line number and column number reached on the output device—the only values passed to the function are guaranteed to be alphanumeric, punctuation, space and newline characters.

Exercise 4.3. Construct a program to test output, where that function is in a separate file from the functions that are used to test it. In the same file as output will be two functions called current_line and current_column which return the values of the line and column counters. Ensure that those counters are made accessible only from the file that contains them.

Exercise 4.4. Write and test a recursive function that performs the admittedly dull task of printing a list of numbers from 100 down to 1. On entry to the function it increments a static variable. If the variable has a value below 100, it calls itself again. Then it prints the value of the variable, decrements it and returns. Check that it works.

Exercise 4.5. Write functions to calculate the sine and cosine of their input. Choose appropriate types for both argument and return value. The series (given below) can be used to approximate the answer. The function should return when the value of the final term is less than 0.000001 of the current value of the function.

sin x = x - pow(x,3)/fact(3) + pow(x,5)/fact(5)...
cos x = 1 - pow(x,2)/fact(2) + pow(x,5)/fact(5)...

Note the fact that the sign in front of each term alternates (--+--+--+...). pow(x,n) returns x to the nth power, fact(n) factorial of n (1 × 2 × 3 × ⋯ × n). You will have to write such functions. Check the results against published tables.


1. Stroustrup B. (1991). The C++ Programming Language 2nd edn. Reading, MA: Addison-Wesley