Friday, November 30

C- Swap Two Numbers Without Using a Temporary Variable



Write a C program to swap two numbers without using a temporary variable.

Swapping interchanges the values of two given variables.

Logic:
step1: x=x+y;
step2: y=x-y;
step3: x=x-y;

Example:
if x=7 and y=4
step1: x=7+4=11;
step2: y=11-4=7;
step3: x=11-7=4;
Thus the values of the variables x and y are interchanged.

Program:

#include <stdio.h>
int main()
{
int a, b;
printf("Enter values of a and b: \n");
scanf("%d %d", &a, &b);
printf("Before swapping a=%d, b=%d\n", a,b);

a = a + b;
b = a - b;
a = a - b;
printf("After swapping a=%d b=%d\n", a, b);
return 0;
}

Output:
Enter values of a and b: 2 3
Before swapping a=2, b=3
The values after swapping are a=3 b=2