Difference: HandsOnFunctions2 ( vs. 1)

Revision 12017-02-16 - JimSkon

Line: 1 to 1
Added:
>
>
META TOPICPARENT name="Spring2017"

Hands On

Overloaded Functions and call by reference

Step 1

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

Swap Two

<-- SyntaxHighlightingPlugin -->
#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!
}
<-- end SyntaxHighlightingPlugin -->

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:

<-- SyntaxHighlightingPlugin -->
#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!
}
<-- end SyntaxHighlightingPlugin -->
Finish and test the program.

Step 4

Try again after removing some of the &
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2019 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback