c program for swapping of two numbers without using temporary variable

By
Advertisement

What is swapping ?


                          The word swapping is generally means as exchanging. That is the value of one variable can be assigned to another variable.
                                    In any programming languages swapping can be done in two ways. The first method is one can use a temporary variable and swapping is done and the second one is without using the temporary variable we can swap them two variable values.



How to perform swapping of two numbers without using temporary variable


            It is any easy and simple task and all it done with the help of two arithmetic operation those are addition and subtraction.

For example if you have two variable x and y, them x stores some unique values and also y stores some unique value.

Case-I:  If   X is greater than Y  Then swapping of two numbers without using temporary variable is carries out as

y=x-y;
x=x-y;
y=x+y;

For example X= 40, Y = 20 then the above expressions are evaluated as

Y = X-Y
    = 40-20
     = 20
then Y=20

X = X-Y
    =  40-20  ( Note: here the values of the Y is the value evaluated in first step)
    = 20
then X=20

So, Finally the two values are get swapped without using temporary variable.

Case-II:  If   Y is greater than X  Then swapping of two numbers without using temporary variable is carries out as

x=y-x;
y=y-x;
x=y+x;
         
It also works like case one except the value of the variable Y is greater than X.


Here is the c program for swapping of two numbers without using temporary variable

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<stdio.h>
#include<conio.h>

void main()
{
int x,y;
clrscr();
printf(" welcome to www.tutoriltpoint.net\n");
printf(" Enter value of X: ");
scanf("%d",&x);
printf("Enter value of y: ");
scanf("%d",&y);

if(x>y)
{
y=x-y;
x=x-y;
y=x+y;
}

else
if(y>x)
{
x=y-x;
y=y-x;
x=y+x;
}

printf(" the value of x after swaping is =%d\n",x);
printf(" the value of y after swaping is=%d\n",y);
getch();
}

The above code is successfully executed and it produces the following output


0 comments:

Post a Comment