Swapping of two numbers without third variable
Posted by Superadmin on September 03 2019 15:44:38

Swapping of two numbers without third variable

 

 

You can also swap two numbers without using third variable. In that case C program will be as follows:

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int a, b;
  6.    
  7.    printf("Input two integers (a & b) to swap\n");
  8.    scanf("%d%d", &a, &b);
  9.    
  10.    a = a + b;
  11.    b = a - b;
  12.    a = a - b;
  13.  
  14.    printf("a = %d\nb = %d\n",a,b);
  15.    return 0;
  16. }

Output of program:
Swap numbers C program output

To understand the logic choose the variables 'a' and 'b' as '7' and '9' respectively and then do what is being done by the program. You can choose any other combination of numbers as well. Sometimes it's an excellent way to understand a program.