WAP that swaps values of two variables with third variable.
Here is you code in C : -
#include <stdio.h>
int main()
{
// Intialisation of numbers and third variable
int n1, n2, temp;
printf("Enter the first number: ");
// Input of 1st variable
scanf("%d", &n1);
printf("Enter the Second number: ");
// Input of 2nd variable
scanf("%d", &n2);
printf("The numbers before swap is n1 = %d and n2 = %d \n", n1, n2);
// Below code is for swapping of two variable.
temp = n1;
n1 = n2;
n2 = temp;
printf("The numbers after swap is n1 = %d and n2 = %d", n1 , n2);
return 0;
}
Output:-
Logic behind swap: -
In the code temp = n1;
n1 = n2;
n2 = temp;
let n1 = 10 , n2 = 20;
Here firstly, we will intialize temp(our 3rd variable) equals to 1st then temp = n1 = 10.
Now, we will use n1 = n2 after which n1 = n2 = 20. Here n1 become equals to 20.
After that, n2 = temp since, temp = 10 hence, n2 = temp = 10.
We can see that after this n1 becomes 20 and n2 becomes 10.
Comments
Post a Comment