+ 3
Simple Program to learn swap using functions.
14 ответов
+ 5
Please show us your attempt first
+ 3
Lawrence Solomon. R I guess you need to use pointers in the function. Sorry, I m not rlly an expert in c++
+ 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
+ 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;
}
+ 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)
+ 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;
}
+ 1
Thanks Ill check using the pointers
0
Ok
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) ;
}
0
The numbers I input are not swaping
0
Thanks
I'll try it right away
0
No I don't use caps it's just the auto capitalize function while typing
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
0
The \n was inside quotes so dont worry about it