function biggest numbers help

Write a function that finds the larger of two integers input (in the main program) but allows you to change the value of the integers in the function using pass by reference. would this be adequate enough or no since it does not allow me to enter different numbers once i put my first numbers in? it takes numbers.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include<iostream>
using namespace std;

int change(int num1, int num2)
{
    int temp=0;
    cout << "Function(before change): " << num1 << " " << num2 << endl;
    temp = num1;
    num1 = num2;
    num2 = temp;
    cout << "Function(after change): " << num1 << " " << num2 << endl;
}

int main()
{
    int num1, num2;
    cout << "Enter your first number: ";
    cin >> num1;
    
    cout << "Enter your second number:";
    cin >> num2;
    
    if (num1 > num2)
    cout << num1 << " is greater than  " << num2 << endl;
    
    if (num2 > num1)
    cout << num2 << " is greater than  " << num1 << endl;
    
    cout << "Main (before change): " << num1 << " " << num2 << endl;
    change (num1, num2);
    cout << "Main (after change): " << num1 << " " << num2 << endl;
    return 0;
}
bump?
1
2
3
4
5
6
7
8
9
int change(int &num1, int &num2) //Pass by reference - use '&'
{
    int temp=0;
    cout << "Function(before change): " << num1 << " " << num2 << endl;
    temp = num1;
    num1 = num2;
    num2 = temp;
    cout << "Function(after change): " << num1 << " " << num2 << endl;
}


If you want to change the values somewhere (other than swapping them) then you need to input values somewhere or calculate new values for the variables.

Does "change" return anything? If not, change it's return type to void
im a little confused
Does the function "change" return any integers? If it doesn't return anything, then you can make the return type "void".

Is swapping the two numbers all you have to do in "change"? I must have misunderstood what exactly your function needs to do.

If we want to change the value of a variable passed to another function (and have the change persist after the function ends), then we need to pass it by reference.

If you want to give those variables a new value some time, then you should put some code in there to input some new values for those variables.
after looking it more i was confused but now i got it. i think the program just wants you to swap values larger over smaller.
If so, then just pass them by reference if you want the change to be permanent (for the ones in main to be permanently changed), or leave them as is if you want the change to be temporary (have the values for the variable return to normal after the function call ends).
Topic archived. No new replies allowed.