# Hands On

Overloaded Functions and call by reference

### Step 1

Consider the following program that calls "swap" to interchange two variables:

### Swap Two

```#include <iostream>
using namespace std;

void swap(int& a, int& b);

int main() {
int one, two
cout << "Program to swap 2 numbers i" << endl;
cout << "Enter first number:";
cin >> one;
cout << "Enter second number:";
cin >> two;

swap(one, two);
cout << one << "," << two << endl;

return 0;
}
void swap(int& a, int& b) {
// You write code!
}```

Paste this into netbeans and write the swap function. Test it out.

### Step 2

Remove the "&" from the formal variable lists. What happens now.

### Step 3

Consider the following simple program to "sort" a few values:

```#include <iostream>
using namespace std;

void order(int& a, int& b);
void order(int& a, int& b, int& c);
void swap(int& a, int& b);

int main() {
int one, two, three;
cout << "Program to order 2 or 3 non-negative numbers in ascending order" << endl;
cout << "Enter first number:";
cin >> one;
cout << "Enter second number:";
cin >> two;
cout << "Enter third number (or negative number to skip):";
cin >> three;

if (three < 0) {
order(one, two);
cout << one << "," << two << endl;
} else {
order(one, two, three);
cout << one << "," << two << "," << three << endl;
}
return 0;
}

void swap(int& a, int& b) {
// You write code!
}

void order(int& a, int& b) {
// You write code!
}

void order(int& a, int& b, int& c) {
// You write code!
}```
Finish and test the program.

### Step 4

Try again after removing some of the &

This topic: SCMP118 > Main > Spring2017 > HandsOnFunctions2
Topic revision: r1 - 2017-02-16 - JimSkon

Copyright © 2008-2020 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback