Problem Statement
Write a C program to Swap the value of two Variables. (Using a 3rd Variable & without Using a 3rd Variable)
Source Code
//Using a 3rd Variable #include <stdio.h> #include <stdlib.h> void main(){ float var1,var2,var3; //Taking inputs printf("Enter Variable 1:\t"); scanf("%f",&var1); printf("Enter Variable 2:\t"); scanf("%f",&var2); //Printing Inputs printf("\n\nBefore Swap\n__________________\nVariable 1:\t%f\nVariable 2:\t%f",var1,var2); //Swap using 3rd variable var3=var1; var1=var2; var2=var3; //Printing Output printf("\n\nAfter Swap\n__________________\nVariable 1:\t%f\nVariable 2:\t%f",var1,var2); } //Not Using a 3rd Variable #include <stdio.h> #include <stdlib.h> void main(){ float var1,var2; //Taking inputs printf("Enter Variable 1:\t"); scanf("%f",&var1); printf("Enter Variable 2:\t"); scanf("%f",&var2); //Printing Inputs printf("\n\nBefore Swap\n__________________\nVariable 1:\t%f\nVariable 2:\t%f",var1,var2); //Swap using 3rd variable var1=var2+var1; var2=var1-var2; var1=var1-var2; //Printing Output printf("\n\nAfter Swap\n__________________\nVariable 1:\t%f\nVariable 2:\t%f",var1,var2); }
Input
Enter Variable 1: 14
Enter Variable 2: 65
Output
Before Swap
Variable 1: 14.000000
Variable 2: 65.000000
After Swap
Variable 1: 65.000000
Variable 2: 14.000000