0% found this document useful (0 votes)
27 views2 pages

Progm

The document discusses different methods for swapping two numbers in C without using a temporary variable. It presents a program that swaps two integers a and b by adding, subtracting, and re-adding them. It also mentions using the XOR operator to swap values by XORing the two variables multiple times. Finally, it notes the disadvantages that these methods only work for integer data types and could cause overflow issues.

Uploaded by

Grijesh Mishra
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views2 pages

Progm

The document discusses different methods for swapping two numbers in C without using a temporary variable. It presents a program that swaps two integers a and b by adding, subtracting, and re-adding them. It also mentions using the XOR operator to swap values by XORing the two variables multiple times. Finally, it notes the disadvantages that these methods only work for integer data types and could cause overflow issues.

Uploaded by

Grijesh Mishra
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 2

C Language Program swap two numbers without using temp or third variable

1 #include<stdio.h> 2 main() 3 { 4 int a, b; 5 printf("Enter two numbers : "); 6 scanf("%d%d",&amp;a,&amp;b); 7 8 a = a + b; 9 b = a - b; 10 a = a - b; 11 12 printf("a = %d\nb = %d\n",a,b); 13 14 } Program To Swap Two Values With Temp Variable Program to Swaping two values */ #include<stdio.h> #include<conio.h> void main() { int a, b, temp; clrscr(); printf("\n Enter the value of a "); scanf("%d",&a); printf("\n Enter the value of b "); scanf("%d",&b); temp=a; a=b; b=temp; printf("\n a = %d , b = %d",a,b); getch(); }

Question: The usual method of swapping two numbers, using a temporaty variable is as shown below.
// Swapping 2 int, X & Y using temporary variable t int t = X; X = Y; Y = t;

How will you swap two numbers without using a temporary variable? Solution:

Using XOR operator


X = X ^ Y; Y = X ^ Y; X = X ^ Y;

The disadvantage of this method is that it can only be applied to low-level data types like integers & characters (char, short, int, long). C & C++ does not allow bit-wise operation on non-integral operands. Using +,- operators
X = X + Y; Y = X - Y; X = X - Y;

This method can only be applied on numerical values. The issue of arithmetic overflow will also be there.

You might also like