WAP that swaps values of two variables without third variable.

 Here is your code in c:-


#include <stdio.h>

int main()
{
    int n1, n2;
    
    printf("Enter the first number: ");
    
    scanf("%d", &n1);
    
    printf("Enter the Second number: ");
    
    scanf("%d", &n2);
    
    printf("The numbers before swap is n1 = %d and n2 = %d \n", n1, n2);
    
    n1 = n1 + n2;
    n2 = n1 - n2;
    n1 = n1 - n2;
    
    printf("The numbers after swap is n1 = %d and n2 = %d", n1 , n2);

    return 0;
}

 Output:-

Logic Behind Swap:-



In the code:-         n1 = n1 + n2;
        
                       n2 = n1 - n2;
       
                        n1 = n1 - n2;

                Let n1 = 10 , n2 = 20;

 

In the first statement n1 = n1 + n2 value of n1 will become 30.

In the second statement n2 = n1 - n2 value of n2 become 30 - 20 = 10 

In the third statement n1 = n1- n2 value of n1 become 30 - 10 = 20

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.