How to swap two numbers without using a temporary variable?



method 1: 
 
#include <stdio.h>
int main()
{
  int x = 10, y = 5;
 
  // Code to swap 'x' and 'y'
  x = x + y;  // x now becomes 15
  y = x - y;  // y becomes 10
  x = x - y;  // x becomes 5
 
  printf("After Swapping: x = %d, y = %d", x, y);
 
  return 0;
}
 
 
 
Method 2 (Using Bitwise XOR)
 
 
#include <stdio.h>
int main()
{
  int x = 10, y = 5;
 
  // Code to swap 'x' (1010) and 'y' (0101)
  x = x ^ y;  // x now becomes 15 (1111)
  y = x ^ y;  // y becomes 10 (1010)
  x = x ^ y;  // x becomes 5 (0101)
 
  printf("After Swapping: x = %d, y = %d", x, y);
 
  return 0;
}
 

Comments

Popular posts from this blog

Write a program to reverse a string?

You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer.