Must use Pass by reference

Hello all, I am faced with a challenge right now, I have an assignment that must be completed and I cannot seem to figure it out. The assignment is as follows:

"1.Write a function that finds the larger of two integers input (in the main program) but calls a function called change which allows you to change the input value of the integers (function must using pass by reference)"

Is it possible to completely change the integers as i am asked to do, I thought I could only swap them when I use a pass by reference statement.
This is my code so far. The program compiles and runs, but it does not return which number is the larger number.

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
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

using namespace std;

int change(int x, int y)
{
     int temp=0;
     cout << "Function(before change): " << x << " " << y << endl;
     temp = x;
     x = y;
     y = temp;
     cout << "Function(after change): " << x << " " << y << endl;
}
int larger ( int x, int y) // Here we define the function
{ 

	 if (x>=y)             // We state that if x is greater or equal to y we will return x
	 {
		 return x;
	 }
	 else                  // Otherwise we will return y
	 {
		 return y;
	 }
}
int main()
{
  int num1,num2;           // We ask for two integers from the user and we return the larger of the two
  int result;
  cout<<"Please Enter Two Integers and I Will Give You the Larger of the Two"<<endl;
  cout<<endl;
  cout<<"The First Integer? :" <<endl; // We ask for Integer 1
  cin >>num1;
  cout<<endl;
  cout<<"The Second Interger? : " <<endl; // We ask for integer 2
  cin >>num2;
  cout<<endl;

  result = change(num1,num2);
  
  system ("Pause");
  return 0;
}
You pass a variable to a function by reference so value_type& variable so whatever changes happens to that variable(param) is written to the reference(memory-address), so you just change the params of your change function, the output-statement(cout<<) before change and after change could be in your main.
1
2
// do the necessary changes  to your function first
void change(int x, int y) // pass the param here by reference, and not by value  

1
2
3
cout << "Function(before change): " << num1<< " " << num2<< endl;
change(num1,num2);
cout << "Function(before change): " << num1<< " " << num2<< endl;
Last edited on
Topic archived. No new replies allowed.