.

.

Wednesday

Swapping of two numbers in C

Swapping means simply exchanging the values of two variable.The 5 different method of swapping have
 shown bellow:

  • Using Third Variable
  • Without Using Third Variable
  • Using  Pointer
  • Using Function using Call by Reference

Using Third Variable:

Assume that you have cup A filled with water and cup B filled with milk, now to swap or exchange content
 of both cups just take cup C and pour the content of cup B into it , now pour the content of cup A into cup
 B and then pour the content of cup C into cup A.
Thus you have swapped the content of cup A and cup B.Similarly using third variable you can swap the
 values of two variable.The c programming code is given bellow..


Code:


#include <stdio.h>
#include <conio.h>
int main()
{
   int x, y, t;



   printf("Enter the value of x and y\n");
   scanf("%d%d", &x, &y);



   printf("Before Swapping\nx = %d\ny = %d\n",x,y);

   t    = x;
   x    = y;
   y    = t;

   printf("After Swapping\nx = %d\ny = %d\n",x,y);

   getch();
}

Out Put:



Without third Variable:


You can also swap two numbers without using third variable.


Code:


include <stdio.h>
include <conio.h>
void main()
{
   int x, y;

   printf("Enter Value for x and y\n");
   scanf("%d%d", &x, &y);

   x = x + y;
   y = x - y;
   x = x - y;

   printf("x = %d\ny = %d\n",a,b);
   getch();

}


Using Pointer:

Code:


#include<stdio.h>

#include<conio.h>

void main()

{

int a=2,b=3;

swap(a,b);
printf("%d%d",a,b);
getch()
}
swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf("%d%d",x,y);
getch()
}

No comments:

Post a Comment