Electro4u 28 Dec 2022 2 views 0 comments C Programming

program to swap two numbers without using a temporary variable.

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 

 

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Bit wise operators Assignment

Bitwise Operators practical assignment: Take runtime input, bit-level manipulation, and different data units r...

AG Anvesh G 27 Sep 2026
Understanding Float and Double Binary Representation in C

Understanding Float and Double Binary Representation in CIntroduction:When we store decimal numbers such as 10...

AG Anvesh G 31 May 2026
Topic-wise C Programming Interview Questions

C Programming Interview Questions – Topic Wise1. IntroductionC programming is one of the most important langu...

AG Anvesh G 30 May 2026