Wednesday, April 15, 2009

Program to interchange or swap the content of two variables (without the use of third variable)

Exercise 7
Two numbers are inputted through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.(Without the help of 3rd variable)
Solution:

#include<stdio.h>
#include<conio.h>


void main()
{
int c,d,x;
printf(“Enter the value of C = ”);
scanf(“%d”, &c);
printf(“\nEnter the value of D = ”);
scanf(“%d”, &d);
printf(“\nSo now C=%d and D=%d”, c,d);
/* Swapping of two variables without the help of 3rd variable */
c=c+d;
d=c-d;
c=c-d;
printf(“\nAnd after swapping C=%d and D=%d”, c, d);
getch();
}
This program is based on very simple logic, let us understand this program with an example.
For example:
Let the value of c=5 & d=9
Initial No Logic c = 5 d = 9
Step 1 c=c+d c = 5 + 9 = 14 d = 9
Step 2 d=c-d c = 14 d = 14 – 9 = 5
Step 3 c=c-d c = 14 – 5 = 9 d = 5
Thus in this Truth-table we see that, we have started the table with the value of c=5 and d=9 and in the end the value of c & d swaps or interchanges, without the help of the 3rd variable.
The output of the program is as follows:
Enter the value of C = 5
Enter the value of D = 9
So now C=5 and D=9
And after swapping C=9 and D=5

No comments:

Post a Comment

Please give your valuable comments or queries if you fell its helpful or if you like the contents of the site. Thanks...