usin swap, need to turn positive number into negative

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include<iostream>

using namespace 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;
}
There is no assignment of c or b in your code.

Why does swap need 2 parameters?

How about this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace 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;
}
swap can only work with 2 parameters, thats the essence of this function I guess, maybe im wrong, but Your code is not working either.
It's working fine for me! What error messages are you getting for my code?
oh it is working, i must have copypasted something wrong :)
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?
Last edited on
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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;

int swap(int x)	
{	
	return 0 - x;
}
	
int main()
{
        int a;
	
	cout << "Enter a positive number: ";    
	cin >> a;

    a = swap(a);	
    cout << a << endl;
    system ("pause");
	return 0;
}


Last edited on
You've been a great help! Thank you a lot!
Topic archived. No new replies allowed.