Programming question

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.

This is what i have so far:

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

Check this out: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
You can ask the user in function subtract whether he wants to modify operands.
You need to use the & in the parameter list.
Last edited on
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 )

plus everything about references
closed account (N36fSL3A)
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.
Topic archived. No new replies allowed.