Tuesday, April 14, 2009

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

Exercise 6
Two numbers are inputted through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.(With 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 with the help of 3rd variable */
x=c;
c=d;
d=x;
printf(“\nAnd after swapping C=%d and D=%d”, c, d);
getch();
}
In this the main part is the logical part, which is also very simple. At first the content of the first variable is kept in the 3rd variable, then the content of the 2nd variable is kept in the first variable and then the content of the third variable is kept in the 2nd variable. Here the 3rd variable is acting as a buffer.
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...