A directory of Objective Type Questions covering all the Computer Science subjects.
Here you can access and discuss Multiple choice questions and answers for various competitive exams and interviews.

C program to swap two numbers without using third variable/

C program to swap two numbers without using third variable

Problem Description

Swapping of two numbers without using third variable can be achieved with the help of sum and subtraction operators. Multiplication and division operators can also be used in place of sum and subtraction.

C program to swap two numbers without using third variable - Source code

#include <stdio.h>
int main()
{
int a, b;
printf("Enter two integers to swap\n");
scanf("%d%d", &a, &b);
printf("Before swapping a = %d , b = %d",a,b);
// Code to swap 'x' and 'y'
a = a + b; // a(5+10) = 15
b = a - b; // b (15-10) = 5
a = a - b; // a (15-5) = 10
printf("\nAfter swapping a = %d and b = %d\n",a,b);
return 0;
}

Program Output

Case 1 :
Enter two integers to swap
5
10
Before swapping a = 5 , b = 10
After swapping a = 10 and b = 5
Case 2 :
Enter two integers to swap
0
10
Before swapping a = 0 , b = 10
After swapping a = 10 and b = 0

Program Explanation

The above program can be better understood by taking an example. Lets take a =5 and b=10 as example.
1. First, the sum value of both the number is assigned to first number i;e a = a+b(5+10) = 15.
2. The second number (10) is subtracted from the sum obtained in the first step and value is assigned to second number. So at this point, first number (a) has value 15 and second number (b) has value (15-10) 5.
3. The swapping is completed when new value of b (5) in second step is subtracted from sum obtained in step 1(value of a) and assigned to a.
You can also try swapping two numbers by using multiplication and division operators. But if you choose one numbers as 0, the program fail as the other number also become zero when multiplied by 0.