C program to swap two values with and without using temporary variable

Hi guys, welcome to another tutorial on C, in this tutorial, we will learn how to swap two different values by writing a program for it in C but first, we will see how to swap two values by using a temporary variable.

Understanding the logic behind the swapping of two variables using a temporary variable:

First we will declare three variables a,b and c and will take input from the user for the two declared variables a and b after that we will assign variable c to the value of a , now c has the value of a and now after that we will assign a to the value of b and then we will assign b to the value of c which now contains the previous value of ‘a’ the piece of code for the will look something like this
c=a;
a=b;
b=c;
Look a the picture below to make the concept much clear:

code for the above logic:

#include<stdio.h> int main(){ int a,b,c; printf("Enter two numbers to swap"); scanf("\%d\%d",&a,&b); printf("Values before swaping a=\%d b=\%d",a,b); c=a; a=b; b=c; printf("Values after swaping a=\%d b=\%d",a,b); return 0; } 

Now let’s make a program to swap two values in C without using a third variable
there are two methods to make such program
1.Addition and subtraction method
2.Multiplication and division method

First-Method

#include<stdio.h> int main(){ int a,b; printf("Enter two numbers to swap"); scanf("\%d\%d",&a,&b); printf("Values before swaping a=\%d b=\%d",a,b); a=a+b; b=a-b; a=a-b; printf("Values after swaping a=\%d b=\%d",a,b); return 0; }

to explain the above logic let’s take some value of variable a and b let say a=10 and b=3
now
a = a+b = 10+3 //new value of a=13
b = a-b = 13-3 //new value of b =10
a = a-b = 13-10 //new value of a= 3

Second method:

#include<stdio.h> int main(){ int a,b; printf("Enter two numbers to swap"); scanf("\%d\%d",&a,&b); printf("Values before swaping a=\%d b=\%d",a,b); a = a*b; b = a/b; a = a/b; printf("Values after swaping a=\%d b=\%d",a,b); return 0; } 

to explain the above logic let’s take some value of variable a and b let say a=10 and b=3
a = a * b //a = 10 * 3 =30
b = a/b // b = 30 / 3 = 10
a= a/b // a = 30 / 10 = 3
Note: in the above method the values of the variables will not change.

Thank you for reading

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don’t forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.


Preorder and Postorder Traversal of binary tree in Python
02 September 2018

Binary Tree in Python
02 September 2018

Image Sharpening by High Pass Filter using Python and OpenCV
17 August 2018

Explaining Register variables in C with examples
17 August 2018

C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий