#include<stdio.h>
/*#include<conio.h>*/
int main()
{
int a,b,c;
/*Accept the values for swapping*/
printf("Enter the two values:");
scanf("%d%d",&a,&b);
/*Print the values before swapping*/
printf("Values before swapping:%d and %d",a,b);
/*Logic for Swapping*/
c=a; /*Here the value of a is stored in variable c*/
a=b; /*Now the value of b is assigned to variable a*/
b=c; /*Finally the value stored in c is assigned to b*/
/* Now, lets print the swapped values*/
printf("Values after swapping:%d and %d",a,b);
return 0;
}
The above Program is using three variables a,b and c. The two values that we enter will be stored in the variables a and b correspondingly. We use a third variable c as the temporary variable to store data temporarily or for some sort of time. Now when c=a is executed the value in a is stored temporarily in c, so that the value will not be lost. Then we execute the next line a=b, this will assign the value of b to a. Then the final line of logic, b=c; this will assign the value in temporary variable c to b, which was the previous value stored in a.
Output
Enter two values:
20 30
Values before swapping: 20 and 30
Values after swapping: 30 and 20
Note: I have commented #include<conio.h> because it would be necessary if you guys need to insert the function getch(); For some Turbo C compiler it is required as to buffer the output to the monitor.
Comments
Post a Comment