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

Popular posts from this blog

WAP to add or to multiply two matrices of order nXn.

WAP that inputs two arrays and saves sum of corresponding elements of these arrays in a third array

WAP to find the minimum and maximum element of the array by using functions.