C Code To Swap Values of Two Variables

By | June 19, 2019

This is a simple C Code To Swap Values of Two Variables using a third temporary variable. This C code uses simple assignment statements to swap the values. We will use a third variable called temp to exchange values of two variables.

First we save the value of first variable in temp variable. Now we will assign the second variable to first variable. In the end we will assign the temp variable to second variable. We will show the values of variables before and after swapping.

/*
Write a C program to swap values of two 
variables with the help of a third temp variable
*/
#include<stdio.h>  
int main()   
{   
  int num1, num2, temp;  
  printf("Enter First Number and Second Number to Swap=");  
  scanf("%d %d",&num1,&num2);  
  printf("before swapping values of variables: First Number = %d\n",num1);  
  printf("before swapping values of variables: Second Number =%d\n",num2);  
/* now we swap values with the help of third variable called temp*/  
  temp = num1;
  num1 = num2;
  num2 = temp;
  
  printf("After swapping: First Number =%d   Second Number = %d",num1,num2);   
  return 0;   
}  

Here is an image showing the sample run and sample output of this C program to exchange / swap the values of two variables using a third variable called temp.

This is a simple C Code To Swap Values of Two Variables using a third temporary variable.

This is a simple C Code To Swap Values of Two Variables using a third temporary variable.

You may also like a related C program to exchange values of two variables without using a third variable with an arithmetic trick.

Loading

One thought on “C Code To Swap Values of Two Variables

  1. Pingback: Swap two variable values without third - EasyCodeBook.com

Leave a Reply

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