I've been stuck working on this program and could really use some help. The program is supposed to be:
Write a C++ program that inputs two integers then calls a function subtract, use pass by reference and allow the user to change his/her input values, then subtract the two numbers and return the difference.
#include <iostream>
usingnamespace std;
int change(int x, int y)
{
int temp=0;
cout << "Function(before change) before subtraction: " << x << " " << y << endl;
temp = x;
x = y;
y = temp;
cout << "Function(after change) before subtraction: " << x << " " << y << endl;
}
int main()
{
int x = 0,y = 0;
char str1[40];
cout << "Enter two integers you would like to subtract." << endl;
cout << "Enter your first number: ";
cin >> x;
cin.getline(str1, 40);
cout << "Enter your second number: ";
cin >> y;
cin.getline(str1, 40);
cout << "Main (before change) after subtraction: " << x - y << endl;
change(x, y);
cout << "Main (after change) after subtraction: " << x - y << endl;
return 0;
}
I can't seem to figure out how to make it so the user can change their input values. Any help is appreciated, thank you!!
When you call a function with a certain parameter, in this case you have integers x and y, the program gives a copy of those variables to the function. If you "pass by reference" you provide a way for this function to manipulate the variable outside of the variable's normal scope. Otherwise the function just has access to the initial value that is passed to the function at the function call.
Just thought i might add this, in the int Change ( int x, int y )
you aren't returning any value so you should probably just have it as void Change( int x, int y )
A reference should do it. By using a reference you change the value of the parameter, you don't then the program makes a copy of it and then changes the copy, leaving the parameter the same.