Friday, 4 April 2014

How To Swap Two Numbers in c Language Program?

Swapping two numbers in C Language is very easy. There are 5 (Five) ways to swap two numbers, you can choose anyone you like. I am mentioning  all one by one below. 
  1. Swap Numbers With Temp (Third) Variable

  2. Swap Numbers Without Temp (Third) Variable

  3. Swap Numbers With Pointers

  4. Swap Numbers With Call By Reference

  5. Swap Numbers With bitwise XOR

Method One  //swap two numbers with third variable

#include<stdio.h>
main()
{
    int valX, valY, valTemp;
    printf("\nEnter the value of X:= ");
    scanf("%d",&valX);
    printf("\nEnter the value of Y:= " );
    scanf("%d",&valY);

    printf("\nBefore Swap\nX=%d\nY=%d",valX,valY);

    valTemp=valX;
    valX=valY;
    valY=valTemp;

    printf("\nAfter Swap\nX=%d\nY=%d",valX,valY);
}

Output of above program is as pasted below: 

Output of Swapping Values





Method Two   //swap two numbers without third variable

#include<stdio.h>
#include<conio.h>
main()
{
     clrscr();
     int x,y;
    printf("\nEnter the value of X:= ");
    scanf("%d",&x);

    printf("\nEnter the value of Y:= " );
    scanf("%d",&y);

    x=x+y;
    y=x-y;
    x=x-y;
    
    printf("\nValues of X, Y After Swap Are:-\n");
    printf("\nValue of  X=%d\nValue of Y=%d",x,y);
    getch();
}

Method Three     //swap two numbers with pointers

#include <stdio.h>
#include <conio.h>
swap(int *valX , int *valY)
{
    int temp;

    temp=*valX;
    *valX=*valY;
    *valY=temp;
}
main()
{
    int a,b;
    clrscr();
    printf("Enter value of A= ");
    scanf("%d", &a);

    printf("\nEnter number B= ");
    scanf("%d", &b);

    printf("\nBefore Swapping\n");
    printf("\nValue of A:= %d ",a);
    printf("\nValue of B:= %d ",b);

    swap(&a,&b);
    printf("\nAfter Swapping\n");
   
printf("\nValue of A:= %d ",a);
    printf("\nValue of B:= %d ",b);

    getch();
}

Method Four  //swap two numbers with call byreference

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

   printf("\nEnter the value of X= %d",x);
   scanf("%d",&x);
   printf("Enter the value of Y= %d",y);
   scanf("%d",&y);

   printf("Before Swapping\nX = %d\nY = %d\n", x, y);
   swap(&x, &y);
   printf("After Swapping\nX = %d\nY = %d\n", x, y);
   return 0;
}
void swap(int *a, int *b)
{
   int temp;
   temp = *b;
   *b   = *a;
   *a   = temp;
}

No comments:

Post a Comment