Lab 4. Call by reference

How to submit your code

Each program (the source code .cpp file) should be submitted through Blackboard (Course Materials > Lab).

You can submit all your programs at the end of the lab session in one submission. This way, we can hopefully avoid the situation when you are quickly writing your program, immediately uploading it to Blackboard, but then, say 10 minutes later, realizing that there is a bug in it.

Basically, submit when you are sure that it will be your final version.

Each program should start with a comment that contains your name and a short program description, for example:

  Author: Your Name 
  Description: Lab 1. Task 1. Hello world

You can submit incomplete programs, but their “incomplete” status must be clearly mentioned in the comment to the program. In this case, also briefly describe what is implemented, and what is not.

Lab 4. Call by reference

Task 1. Swap

Write a function void swap(int &x, int &y) that gets two integer variables passed by reference, and swaps the values assigned to those integer variables, so if we define two integers a = 5 and b = 10 and call swap(a,b):

int a = 5, b = 10;
swap(a, b);
// the values in a and b have been swapped,
// so now, a == 10, and b == 5

we get a == 10, and b == 5.

To test the function, complement your program with a main function that calls

int a = 5, b = 10;
cout << "a = " << a << " b = " << b << endl;
swap(a, b);
cout << "a = " << a << " b = " << b << endl;
swap(a, b);
cout << "a = " << a << " b = " << b << endl;

The result should look as follows:

a = 5 b = 10
a = 10 b = 5
a = 5 b = 10

Task 2. Simplifying fractions

Write a function void simplify(int &n, int &d) that takes two integer parameters, numerator n and denominator d, passed by reference, and simplifies this fraction.

That is, it updates the values of n and d so that the ratio n/d remains the same, but the absolute value of the demoninator is the smallest possible.

Make sure that your program can handle the case when n and/or d are negative. Also, you may assume that d is never equal to zero;

Complement your program with a main function that tests how your function works.

Task 3. Sorting three integers

Write a function void sort(int &a, int &b, int &c) that sorts the values of the integer parameters passed by reference, so that they become arranged in the ascending order a <= b <= c.

Feel free to use the previously defined function swap.

Complement your program with a main function that tests how the function sort works.

Task 4. Bonus

In this task, we don’t use call by reference. Call by value function seems to be more natural for this application.

Also, the task is supposed to be quite challenging.

Write a function int reverse(int x) that reverses the digits of its argument. You may assume that the argument is a positive integer.

For example

cout << reverse(23456) << endl;

Should print