Hi again! now i need to turn positive number into negative using swap. program should look something like this, i have to use prototype, just the issue is, to determine '-'. right now this is not working properly.
#include<iostream>
usingnamespace std;
void swap(int a, int b)
{
a=b;
b=(-a);
}
int main()
{
int c, b;
cin>>c;
swap(c,b);
cout<<c<<endl;
system ("pause");
return 0;
}
#include<iostream>
usingnamespace std;
int swap(int a)
{
return 0 - a;
}
int main()
{
int a;
cout << "Enter a positive number: ";
cin >> a;
a = swap(a);
cout << a << endl;
system ("pause");
return 0;
}
can You please explain? why is this working only when this line is like this a = swap(a);? and if you remove a= than it gives you same positive number back?
Because swap returns an integer (the negative version of the parameter).
a = swap(a); assigns the value returned by swap to the variable a.
swap(a) alone will pass a to swap() but nothing will be returned, the a within swap() is a different local variable to the a in main(), the a in swap() is modified but not the a in main().
Maybe it's clearer if we call the swap() parameter x instead?