Write a program two swap two number using third or without using third variable. For example if we have two num1=5 and num2 =6 then after swapping they should be changed to num1=6 and num2=5.
Method 1 (Using Third variable )
Method 2 (Without using third variable )
Method 3 (In one line)
Method 4 (Using XOR Operation )
Please comment if you like the above post or if you find any mistake.
Method 1 (Using Third variable )
#include <stdio.h>
int main(void) {
int num1, num2, temp;
printf("Enter the two
number");
scanf("%d%d", &num1,
&num2);
//swapping two
number using third variable
temp
= num1;
num1
= num2;
num2
= temp;
//printing two
number after swapping
printf("\n%d", num1);
printf("\n%d", num2);
return 0;
}
Method 2 (Without using third variable )
#include <stdio.h>
int main(void) {
int num1, num2, temp;
printf("Enter the two
number");
scanf("%d%d", &num1,
&num2);
//swapping two
number without using third variable
num1
= num1 + num2;
num2
= num1 - num2;
num1
= num1 - num2;
//printing two
number after swapping
printf("\n%d", num1);
printf("\n%d", num2);
return 0;
}
Method 3 (In one line)
#include <stdio.h>
int main(void) {
int num1,num2,temp;
printf("Enter the two
number");
scanf("%d%d",&num1,&num2);
//swapping two
number in one line
num1=(num1+num2)-(num2=num1);
//printing two
number after swapping
printf("\n%d",num1);
printf("\n%d",num2);
return 0;
}
Method 4 (Using XOR Operation )
#include <stdio.h>
int main(void) {
int num1,num2,temp;
printf("Enter the two
number");
scanf("%d%d",&num1,&num2);
//swapping two
number using XOR operation
num1
^= num2;
num2
^= num1;
num1
^=num2;
//printing two
number after swapping
printf("\n%d",num1);
printf("\n%d",num2);
return 0;
}
Please comment if you like the above post or if you find any mistake.
// check this also
ReplyDelete#include
int main()
{
int a=5,b=10;
printf("before swap a=%d b=%d",a,b);
b=(a*b)/(b=a);
printf("after swap a=%d b=%d",a,b);
return 0;
}