Tuesday, September 16, 2014

Swap numbers using C

1)Without using third variable

Source code:

#include <stdio.h> 
int main()
{
 int a, b; 
   printf("Enter two integers to swap:\n");
   scanf("%d%d", &a, &b);
 
   a = a + b;
   b = a - b;
   a = a - b;
 
   printf("After swapping:\n a = %d\n b = %d\n",a,b);
   return 0;
}

Output:

Enter two integers to swap:
      6
      5
      After swapping:
      a=5
      b=6

Explanation:

To understand above logic enter 6 and 5.Thus first value will be at variable 'a' and second will be at 'b'.Then swapping (means exchange) will give you the result i.e: a=5 and b=6.
2.