W25 _ Lab 05 _ Pointers and Advanced Functions
W25 _ Lab 05 _ Pointers and Advanced Functions
As you have seen in lectures, pointers (also known as pointer variables) are special
variables that are used to store addresses rather than values. Some C programming
tasks are performed more easily with pointers, and other tasks, such as having
functions that produce multiple results, cannot be performed without using
pointers. So it becomes necessary to learn how to work with pointers to become a
proficient C programmer.
The learning objective of this lab is to become familiar with pointers and their use
in writing functions that give multiple results or functions that return values with
pointers alone.
Reading and related topics: Course slides Lesson 06. Book chapter 6.
Write algorithms and complete C programs to solve the following two problems.
Follow the template for each problem and make sure your programs are well
documented (comments).
Save your report in .pdf format and submit it on D2L. You should submit your
lab at the end of your lab session or soon after. In all cases it must be submitted
before the deadline indicated in the D2L dropbox or it will not be accepted for
marking.
CPS188 > Lab 05 > Pointers and Advanced Functions 2
Note that you are only allowed to use the material covered so far. For example, the
use of arrays, and sort functions is not permitted.
Problem 1: Write one C function (and only one) that takes in two integer
numbers and gives back four "results":
1) the average of the two numbers
2) the sum of the squares of the two numbers
3) the absolute value of the square of the difference between the two numbers
4) the square root of the sum of the squares of the two numbers.
In the main program, ask the user for the two integer numbers, call the function
and display the four results clearly labeled. You cannot do any of the calculations
in the main program.
Test your program with the following sets of input data:
56 78
45 -20
-80 -40
8 0
Problem 2: Let's assume that you could travel to the Moon by car traveling at 100
km/h. How long would that take to get there? How about going to Mars or
Venus? If you go there by rocket with a higher speed, it would obviously take less
time.
To solve this problem you will need to write three user-defined functions, one for
each destination. Each of the functions will take the traveling speed in km/h as the
argument and give the time (in hours) it will take to get to the destination.
Note that because there are minimum (perigee) and maximum (apogee) distances
between the Earth, the Moon, Mars and Venus, you will need to calculate the
minimum and maximum travel times so the three functions will each produce
two results. Use pointers to return the results to the main function. Do not print
CPS188 > Lab 05 > Pointers and Advanced Functions 3
Run your program with the following speeds: 100 km/h (car), 500 km/h
(airplane), and 41000 km/h (rocket).
Have fun!