- Swapping two numbers without third variable.
#include<stdio.h> int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
Output
Before swap a=10 b=20After swap a=20 b=10
2. Swapping two string
#include<stdio.h> #include<string.h>
main()
{
char s1[10], s2 [10], s3 [10];
printf("Enter String 1\n");
gets (s1);
printf("Enter String 2\n");
gets (s2);
printf("Before Swapping\n");
printf("String 1: %s\n", s1);
printf("String 2: %s\n", s2);
strcpy(s3, s1);
strcpy(s1, s2);
strcpy(s2, s3);
printf("After Swapping: \n");
printf("String 1: %s\n",s1);
printf("String 2: %s\n", s2);
}
Out put
Enter String 1Sookshmas
Enter String 2
Laptop
Before Swapping
String 1: Sookshmas
String 2: Laptop
After Swapping:
String 1: Laptop
String 2: Sookshmas
3. Swapping two numbers with pointers
# include < stdio.h >
int main( )
{
int a, b, temp ;
int *p1, *p2 ;
printf(" Enter the first number : ") ;
scanf("%d ", & a) ;
printf("\n Enter the second number : ") ;
scanf("%d ", & b) ;
printf("\n Two Number before swapping :%d, %d ", *p1, *p2) ;
temp = *p1 ;
*p1 = *p2 ;
*p2 = temp ;
printf("\n Two Number after swapping :%d, %d ", *p1, *p2) ;
return 0;
}
Output
Enter the first number:10Enter the second number:15
Two Number before swapping:10,15
Two Number after swapping:15,10