/* Swap the values of two variables without using third variable */
Method 1 (Using Arithmetic Operators)
#include<stdio.h>int main ( )
{
int a;
int b;
printf("Type value of A : ");
scanf("%d",&a);
printf("\nType value of B : ");
scanf("%d",&b);
a = a + b;
b = a - b;
a = a - b ;
printf("A : %d",a);
printf("\nB : %d",b);
return 0;
}
Method 2 (Using Multiplication and division Operators)
#include<stdio.h>
int main ( )
{
int a;
int b;
printf("Type value of A : ");
scanf("%d",&a);
printf("\nType value of B : ");
scanf("%d",&b);
a=a*b;
int main ( )
{
int a;
int b;
printf("Type value of A : ");
scanf("%d",&a);
printf("\nType value of B : ");
scanf("%d",&b);
a=a*b;
b=a/b;
a=a/b;
printf("A : %d",a);
printf("\nB : %d",b);
return 0;
}
printf("A : %d",a);
printf("\nB : %d",b);
return 0;
}
Method 3 (Using Bitwise XOR)
#include<stdio.h>
int main ( )
{
int a;
int b;
printf("Type value of A : ");
scanf("%d",&a);
printf("\nType value of B : ");
scanf("%d",&b);
int main ( )
{
int a;
int b;
printf("Type value of A : ");
scanf("%d",&a);
printf("\nType value of B : ");
scanf("%d",&b);
a=a^b;
b=a^b;
a=a^b;
printf("A : %d",a);
printf("\nB : %d",b);
return 0;
}
printf("A : %d",a);
printf("\nB : %d",b);
return 0;
}
Method 4 (Using Functions and Pointers)
#include<stdio.h>
void swap(int *x,int *y)
{
if(*x==*y)
return;
*x = *x + *y;
*y = *x - *y;
*x = *x - *y;
}int main ( )
{
int a;
int b;
printf("Type value of A : ");
scanf("%d",&a);
printf("\nType value of B : ");
scanf("%d",&b);
printf("Before Swapping A=%d B=%d",a,b);
swap(&a,&b);
printf("After Swapping A=%d B=%d",a,b);
return 0;
}
void main(){
printf("After Swapping A=%d B=%d",a,b);
return 0;
}
Method 5 (Using Assignment Operator)
void main(){
int
a=10,b=30;
a=a+b-(b=a);
//10+30-(10) a becomes 30
// b is
assigned with 10 in the same line of code
printf("a= %d\nb=
%d",a,b);
}
Method 6 (Using Bitwise Operator)
#include<stdio.h> void main() { int a=14,b=4; a=b-~a-1; b=a+~b+1; a=a+~b+1; printf("a=%d\nb= %d",a,b); }
No comments:
Post a Comment