Monday 29 May 2017

Swapping two Numbers ~ GNIITHELP

Program to Swap Variable's Numeric Values

In this program we will swap values of two variables. The values are numeric and we will swap them using different techniques(some tricky ones too). Let's start with the simplest technique, which is by using a temporary variable
#include<stdio.h>
#include<conio.h>

void main()
{
   int x=10, y=15, temp;
   temp = x;
   x = y;
   y = temp;
   printf("x= %d and y= %d", x, y);
   getch();
}
Output
x= 15 and y= 10 

Program to Swap two Numbers without using Third variable

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

void main()
{
   int x=10, y=15;
   x = x+y-(y=x);
   printf("x= %d and y= %d",x,y);
   getch();
}
Output
x= 15 and y= 10 

Program to Swap two Numbers using Bitwise Operator

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

void main()
{
   int x=6, y=4;
   x = x^y;
   y = x^y;
   x = x^y;
   printf("x= %d and y= %d", x, y);
   getch();
}
Output
x= 4 and y= 6 

Program to Swap two Numbers using Division and Multiplication

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

void main()
{
   int x=6, y=4;
   x = x*y;
   y = x/y;
   x = x/y;
   printf("x= %d and y= %d", x, y);
   getch();
}
Output
x= 4 and y= 6 

No comments:

Post a Comment