program to swap two numbers without using a temporary variable.

29 Dec 2022 Balmiki Kumar 0 C Programming

C Programming: Swap Numbers without Temporary Variable

A program to swap two numbers without using a temporary variable refers to a programming logic or algorithm that allows the values of two variables to be exchanged without using an additional variable for temporary storage.

In such a program, the values of the variables are manipulated using arithmetic operations or logical operations in a way that the original values are swapped. This technique is often used to optimize memory usage or for situations where using an additional temporary variable is not possible or not desirable

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.

Swap Two Numbers in C: Without Temporary Variable

#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);
 /*Swapping logic */
 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 

 

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.