Search code examples
c++referencenumbersswap

Number swapping: How do I get this program's main function to call the reference function?


So I have this program where it swaps the two numbers entered by the user, only problem is that I can't get the main function to call the function that does the swapping, here's the code:

#include <iostream>
using namespace std;

float first, 
second;

void swap(float first, float second);

int main()
{

    // Prompt user to enter the first number. 
    cout << "Enter the first number" << endl;
    cout << "Then hit enter" << endl;
    cin >> first;

    // Prompt user to enter the second number. 
    cout << "Enter the second number" << endl;
    cout << "Then hit enter" << endl;
    cin >> second;

    // Echo print the input.
    cout << endl << "You input the numbers as " << first
         << " and " << second << endl;
    
  swap(first, second);
  
  return 0;
}



void swap(float &number1, float &number2)
{
  number1 = number2;
    number2 = number1;
    // Output the values.
    cout << "After swapping, the values of the two numbers are "
         << number1 << " and " << number2 << endl;
}

Solution

  • In your function declaration you have first and second passed by value:

    void swap(float first, float second);
    

    This needs to be passed by reference, as given in your function definition:

    void swap(float &number1, float &number2);
    

    Just as a heads up, you'll notice that when you run it it'll print out number2 twice. When you're swapping values, you need a third (temporary) variable.

    void swap(float &number1, float &number2)
    {
        float temp = number1;
        number1 = number2;
        number2 = temp; // We change this to temp because you already changed number1 to
                        // equal number2. If we set number2 = number1, we'd just end up
                        // with the value we started with for number2.
        // Output the values.
        cout << "After swapping, the values of the two numbers are "
             << number1 << " and " << number2 << endl;
    }
    

    Hope this helps! Good luck in class