C

Swapping Of Two Numbers Without Temporary Variable in C

In this tutorial, we are going to see how to swap two numbers without using a temporary variable in C. In computer science, it is a common operation to swap two variables, and even if some languages implement this functionality, we often see programmers recode the swap. We can make a permutation without a temporary variable with just two operations.

a = a + b - b
b = a + b - a

OR:

a = (a + b) - b
b = (a + b) - a

(a + b) can be used as a temporary variable.

There are three ways to swap two numbers in C, by using temporary variable, without temporary variable, or by creating a function.
 

 

Swapping Of Two Numbers Without Temporary Variable Using Pointers
#include <stdio.h>

void swap(int *,int*);

int main ()
{

  int a, b;
 
  printf("Enter two numbers: ");
  scanf("%d%d", &a, &b);

  printf("Before Swapping : a=%d,b=%d\n",a,b);

  swap(&a,&b);

  printf("After Swapping : a=%d,b=%d\n",a,b);
  return 0;
}

void swap(int *a,int *b){

  *a += *b;
  *b = *a-*b;
  *a = *a-*b;
}

Output:

Enter two numbers: 1 2
Before Swapping : a=1,b=2
After Swapping : a=2,b=1

 

 

Swapping Of Two Numbers Without Temporary Variable Using Macro
#include <stdio.h>

#define SWAP(x,y) x ^= y, y ^= x, x ^= y


int main ()
{
  int a, b;
 
  printf("Enter two numbers: ");
  scanf("%d%d", &a, &b);

  printf("Before Swapping : a=%d,b=%d\n",a,b);

  SWAP(a,b);

  printf("After Swapping : a=%d,b=%d\n",a,b);
  return 0;
}

Output:

Enter two numbers: 1 2
Before Swapping : a=1,b=2
After Swapping : a=2,b=1

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *