- By * and /
Program 1: Using + and -
Let's explore a basic C illustration demonstrating how to interchange two values without the need for a third variable.
Example
Example
#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b;//a=30 (10+20)
b=a-b;//b=10 (30-20)
a=a-b;//a=20 (30-10)
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
Output:
Output
Before swap a=10 b=20
After swap a=20 b=10
Program 2: Using * and /
Let's explore another instance of exchanging the positions of two numbers by utilizing the * operator for multiplication and the / operator for division.
Example
Example
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a*b;//a=200 (10*20)
b=a/b;//b=10 (200/20)
a=a/b;//a=20 (200/10)
system("cls");
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
Output:
Output
Before swap a=10 b=20
After swap a=20 b=10