C Program to swap values of two no.s without using third variable
Objective
Write a C program to swap the values of two variables WITHOUT using a third variable.
Algorithm / Approach
- Declare two integer variables:
aandb. - Read the values from the user.
- Perform the addition swap logic:
- 1.
a = a + b(Now a holds the total sum) - 2.
b = a - b(Subtracting the original b from the sum leaves the original a, which is stored in b) - 3.
a = a - b(Subtracting the new b from the sum leaves the original b, which is stored in a).
main.c
#include<stdio.h>
int main( ) {
int a, b;
printf("Enter Values for A and B: ");
scanf("%d%d",&a,&b);
printf("BEFORE :");
printf("A=%d B=%d\n",a,b);
a = a+b;
b = a-b;
a = a-b;
printf("AFTER :");
printf("A=%d B=%d\n",a,b);
return 0;
}
Expected Output
Enter Values for A and B : 17 19 BEFORE: A=17 B=19 AFTER : A=19 B=17
Explanation of the Program
- This is a classic interview question. It proves that you can swap two variables using pure arithmetic logic rather than relying on extra memory.
- While clever, this method can theoretically cause an Integer Overflow if the sum of
aandbexceeds the maximum value an integer can hold. In production code, using a temporary variable is usually safer and faster.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Integer Overflow: If a and b are very large numbers, a+b might exceed the capacity of the int data type, resulting in garbage values.