+ 3

Simple Program to learn swap using functions.

7th Mar 2019, 11:57 AM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
14 ответов
+ 5
Please show us your attempt first
7th Mar 2019, 11:59 AM
Seniru
Seniru - avatar
+ 3
Lawrence Solomon. R I guess you need to use pointers in the function. Sorry, I m not rlly an expert in c++
7th Mar 2019, 12:12 PM
Seniru
Seniru - avatar
+ 3
Lawrence Solomon. R also there is another method which you do not need an extra variable. Try it out too! x^=y^=x; //inside swap function
7th Mar 2019, 12:24 PM
Seniru
Seniru - avatar
+ 2
Lawrence Solomon. R your code had many errors. And don't use capital letters where you don't have to use Modified and working code #include <iostream> using namespace std; int main() { int a=10; int b=20; printf("a=%d, b=%d",a, b); swap(a,b); printf("\na=%d, b=%d",a, b); return 0; } void swap(int &x,int &y) { int c; c=x;y=x;y=c; }
7th Mar 2019, 12:22 PM
Seniru
Seniru - avatar
+ 2
Lawrence Solomon. R check that you have swapped the arguments in the printf functions manually. So you will get the swapped answer of swapped answer (meaning no effect)
7th Mar 2019, 12:39 PM
Seniru
Seniru - avatar
+ 1
That's because à and b aren't modify. You have to pass them by reference : void swap(int& x, int& y) { int c; c = y, y = x, x = c; }
7th Mar 2019, 12:13 PM
Théophile
Théophile - avatar
+ 1
Thanks Ill check using the pointers
7th Mar 2019, 12:13 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
0
Ok
7th Mar 2019, 12:00 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
0
Void main { int a=10,b=20; Void swap(int,int); Printf("a=%d, b=%d",a, b); Swap(a,b); Printf("a=%d, b=%d",a, b); } Void swap(intx,inty) { Intc; c=x;y=x;y=c; Printf("x=%d, y=%d",x, y) ; }
7th Mar 2019, 12:10 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
0
The numbers I input are not swaping
7th Mar 2019, 12:10 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
0
Thanks I'll try it right away
7th Mar 2019, 12:15 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
0
No I don't use caps it's just the auto capitalize function while typing
7th Mar 2019, 12:24 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
0
I do have one more doubt In the above code you gave me After swap I made a small change Where I coded as printf(\n "a=%d, b=%d", b, a); I got back a=10.b=20 why is that
7th Mar 2019, 12:30 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar
0
The \n was inside quotes so dont worry about it
7th Mar 2019, 12:32 PM
Lawrence Solomon. R
Lawrence Solomon. R - avatar