Wednesday, December 31, 2014

Swapping of two numbers in C

Swapping of two numbers in c


#include <stdio.h>
#include <conio.h>
 
void main()
{
   int x, y, temp;
 
   printf("Enter the value of x and y\n");
   scanf("%d%d", &x, &y);
 
   printf("Before Swapping\nx = %d\ny = %d\n",x,y);
 
   temp = x;
   x    = y;
   y    = temp;
 
   printf("After Swapping\nx = %d\ny = %d\n",x,y);
 
   getch();

}


Output:
Enter the value of x and y
9
7
Before Swapping x= 9
y= 7

After swapping x= 7
y=9

Swapping of two numbers without third variable

#include <stdio.h>
#include <conio.h> 
void 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("a = %d\nb = %d\n",a,b);
   
getch();
}

Output:
Enter two integers to swap
9
7

a=7
b=9

No comments:

Post a Comment