Write a program to swap two numbers without using the third variable?

#include
#include
main()
{
int a=10, b=20; //declaration of variables.
clrscr(); //It clears the screen.
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);
getch();
}

Certainly! Here’s a program in C to swap two numbers without using a third variable, using arithmetic operations:

c
#include <stdio.h>

int main() {
int a, b;

printf("Enter two numbers: ");
scanf("%d %d", &a, &b);

printf("Before swapping: a = %d, b = %d\n", a, b);

// Swapping without using a third variable
a = a + b;
b = a - b;
a = a - b;

printf("After swapping: a = %d, b = %d\n", a, b);

return 0;
}

Explanation:

  • Initially, the values of a and b are stored.
  • To swap a and b without using a third variable:
    1. a is assigned the sum of a and b.
    2. b is assigned the difference between the new value of a (which is a + b) and the original value of b. This effectively stores the original value of a in b.
    3. Finally, a is assigned the difference between the new value of a (which is now a + b) and the new value of b (which was the original value of a). This effectively stores the original value of b in a.
  • After these operations, a and b are swapped.