Swap Two Values without Third Variable In C

 

 Swap Two Values without Third Variable In C 



#include <stdio.h>

int main() {
    int a, b ;

    // Ask user to enter two numbers
    printf("Enter Value of a & b: ");
    scanf("%d%d", &a,&b);


    // Add the two numbers
a = a + b ;
    b = a - b ;
    a = a - b ;

    // Display the result
    printf("value after Swap of : a=%d and b=%d",a,b);

    return 0;
}


Detailed Explanation:

  1. Initial Input:

    • The program prompts the user to enter two integer values for a and b.
    • Example: Suppose the user enters a = 5 and b = 3.
  2. Step-by-Step Execution:

    • Step 1: a = a + b;
      • This calculates the sum of a and b and stores it in a.
      • For a = 5 and b = 3, it becomes a = 5 + 3 = 8.
    • Step 2: b = a - b;
      • This calculates the original value of a by subtracting the current value of b from the current value of a.
      • For a = 8 and b = 3, it becomes b = 8 - 3 = 5.
    • Step 3: a = a - b;
      • This calculates the original value of b by subtracting the current value of b (which is now the original value of a) from the current value of a.
      • For a = 8 and b = 5, it becomes a = 8 - 5 = 3.
  3. Final Values:

    • After these operations, the values of a and b are swapped.
    • a is now 3 and b is now 5.
  4. Output:

    • The program prints the swapped values.
    • The output will be: value after Swap of : a=3 and b=5.

Example Run:

Enter Value of a & b: 5 3 value after Swap of : a=3 and b=5

This method of swapping values works by manipulating the sums and differences of the variables, effectively exchanging their values without the need for a temporary storage variable.

Post a Comment

0 Comments