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.
#include <iostream>
usingnamespace 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