C

Swap Two Numbers Using Temporary Variable in C

In this tutorial, we are going to see how to swap two numbers using temporary variable in C. The best option for swapping two variables in C is to use a third temporary variable.

int tmp = a;
a = b;
b = tmp;

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

 

Swap Two Numbers Using Temporary Variable in C
#include <stdio.h>
 
int main()
{
  int a, b, tmp;
 
  printf("Enter two numbers: ");
  scanf("%d%d", &a, &b);
 
  printf("Before Swapping\nA = %d\nB = %d\n", a, b);
 
  tmp = a;
  a = b;
  b = tmp;
 
  printf("After Swapping\nA = %d\nB = %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 *