Saturday, 28 April 2012

Swaping

          
                          C program to swap two numbers with and without using third variable, swapping in c using pointers and functions (Call by reference) , swapping means interchanging. For example if in your c program you have taken two variable a and b where a = 4 and b = 5, then before swapping a = 4, b = 5 after swapping a = 5, b = 4
In our c program to swap numbers we will use a temp variable to swap two numbers. Swapping is used in sorting that is when we wish to arrange numbers in a particular order either in ascending order or in descending order.


   swaping of two number in c :-


#include<stdio.h>
#include<conio.h>
void main()
{
   int x, y, temp;
   printf("Enter the value of x and y ");
   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();
}


Swapping of two numbers without third variable:-

#include<stdio.h>
#include<conio.h>

void main()
{
   int a, b;

   printf("Enter two numbers to swap ");
   scanf("%d%d",&a,&b);

   a = a + b;
   b = a - b;
   a = a - b;
    
printf("a = %d\nb = %d\n",a,b);

   getch();
}

swap two number using pointers :-


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


 swapping number using call by reference:-

#include<stdio.h>
#include<conio.h>
void swap(int*, int*);

void main()
{
   int x, y;

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

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

   swap(&x, &y);

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

   getch();
}

void swap(int *a, int *b)
{
   int temp;

   temp = *b;
   *b = *a;
   *a = temp;
}

output :-

No comments:

Post a Comment