Swap two variable values without third

By | June 19, 2019

Here is a C program Code to swap or exchange two variable values without third variable. This program uses a simple mathematical trick.

Suppose we have two variables with values:

num1 =10, num2 = 20

num1 = num1 + nm2        => num1 =10+20 = 30

num2 = num1 -num2      => num2 = 30-20 = 10 (swapped)

num1 = num1 – num2     => num1= 30-10 = 20(swapped)

We can easily check that after using these three mathematical statements, the values of two variables have been swapped successfully.

/*
Write a C program to swap values of two 
variables without using a third 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 a mathematical trick*/  
  num1 = num1 + num2;
  num2 = num1 - num2;
  num1 = num1 - num2;
  printf("After swapping: First Number =%d   Second Number = %d",num1,num2);   
  return 0;   
}  

Here is an image to show the sample run and output of this program to exchange the values of two variables without third variable.

Here is an image to show the sample run and output of this program to exchange the values of two variables without third variable.

Here is an image to show the sample run and output of this program to exchange the values of two variables without third variable.

You may also like the related C program to exchange values of two variables using third variable called temp.

Loading

One thought on “Swap two variable values without third

  1. Pingback: C Code To Swap Values of Two Variables - EasyCodeBook.com

Leave a Reply

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