Tuesday, December 23, 2014

C program to swap values of two variables


This C program will ask to provide two values and they will be stored into two different variables. Later, the stored value will be swapped and finally the swapped values will be displayed. For example, the first value will be stored into a variable v1 and the second value will be stored into another variable v2. To swap them, we have to use another variable temp. So, first of all we will transfer the value stored in v1 variable into the variable temp using the line temp = v1;.

Then we will transfer the stored data of the variable v2 into the variable v1 by the line v1 = v2;. Finally we will transfer the data of the temp variable into the variable v2 using the line v2 = temp;. Thus the data of those two variables will be swapped.

#include<stdio.h>

main()
{
int v1, v2, temp;

printf("Enter the first value: ");
scanf("%d",&v1);

printf("Enter the second value: ");
scanf("%d",&v2);

printf("\nBefore swaping...");
printf("\nThe stored value in v1 is: %d",v1);
printf("\nThe stored value in v2 is: %d",v2);

temp = v1;
v1 = v2;
v2 = temp;

printf("\n\n\nAfter swaping...");
printf("\nThe stored value in v1 is: %d",v1);
printf("\nThe stored value in v2 is: %d",v2);

}

No comments:

Post a Comment