+ 9
C program for Swapping two numbers
8 Réponses
+ 8
Swapping two numbers
#include < stdio.h >
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x;
x = y;
y = temp;
/*using temp to swap
storing x to temp and y to x then moving temp to y*/
printf("After Swapping\nx = %d\ny = %d\n",x,y);
return 0;
}
+ 2
if yiu don't want use a third variable temp try this one instead
/* same code */
a=a+b;
b=a-b;
a=a-b;
/* same code */
+ 2
You can also use this code using bitwise xor operator (^)
a = a ^ b;
b = a ^ b;
a = a ^ b;
I think this is the best way to swap 2 numbers
+ 2
a=a+b-(b=a)
this is a simple one line logic
without using a third variable
0
{
int a,b;
printf("enter number");
scanf("%d%d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("a=%d b=%d",a,b);
}
0
by using:-
a=(a+b);
b=(a-b);
a=(a-b);
swaps the two numbers....
if a=2; and b=10;
then by using swaps method as mentioned above...
a=10; and b=2;
0
it can be done by more than 20 ways....
0
Swapping two numbers
#include < stdio.h >
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
x=x+y;
y=x-y;
x=x-y;
/*without using temp to swap
storing x to temp and y to x then moving temp to y*/
printf("After Swapping\nx = %d\ny = %d\n",x,y);
return 0;
}