Friday, 1 August 2014

Swap two numbers

Swap two numbers using third variables

/********************************************************
               Swap of Two Number
********************************************************/
#include< stdio.h>
#include< conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter value of a:= ");
scanf("%d",&a);
printf("Enter value of b:= ");
scanf("%d",&b);
c=a;
a=b;
b=c;
printf("After swap a=: %d b=: %d",a,b);
getch();
}
Output
images

Swap two numbers without using third variable

/********************************************************
               Swap of Two Number
********************************************************/
#include< stdio.h>
#include< conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter value of a:= ");
scanf("%d",&a);
printf("Enter value of b:= ");
scanf("%d",&b);
a=a+b;
b=a-b;
a=a-b;
printf("After swap \na=: %d\nb=: %d",a,b);
getch();
}
Output
images

Swap two numbers using Pointers

/********************************************************
               Swap of Two Number
********************************************************/
#include< stdio.h>
#include< conio.h> 
int main()
{
  int x,y,*b,*a,temp;
  clrscr();
  printf("Enter any two number : ");
  scanf("%d%d",&x,&y);
  printf("Before swaping : x= %d and y=%d\n",x,y);
  a = &x;
  b = &y;
  temp = *a;
  *a = *b;
  *b = temp;
  printf("After swaping : x= %d and y=%d\n",x,y);
  getch();
}
Output
Enter any two number : 10 20
Before Swaping : x=10 and y=20
After swaping : x=20 and y=10

Swap two numbers using call by Reference

/********************************************************
               Swap of Two Number
********************************************************/
#include< stdio.h>
#include< conio.h> 
int main()
{
  int x,y,*b,*a,temp;
  clrscr();
  printf("Enter any two number : ");
  scanf("%d%d",&x,&y);
  swap(&x, &y);
  printf("Before swaping : x= %d and y=%d\n",x,y);
 }
 void swap(int *a, int *y)
 {
  int temp;
  temp = *a;
  *a = *b;
  *b = temp;
  printf("After swaping : x= %d and y=%d\n",x,y);
  getch();
}
Output
Enter any two number : 30 20
Before Swaping : x=30 and y=20
After swaping : x=20 and y=30

Swap two numbers using Bitwise XOR

/********************************************************
               Swap of Two Number
********************************************************/
#include< stdio.h>
#include< conio.h> 
int main()
{
  int x, y;
  clrscr();
  printf("Enter any two number : ");
  scanf("%d%d",&x,&y);
  printf("Before swaping : x= %d and y=%d\n",x,y);
  x = x ^ y;
  y = x ^ y;
  x = x ^ y;
  printf("After swaping : x= %d and y=%d\n",x,y);
  getch();
}
Output
Enter any two number : 4 5
Before Swaping : x=4 and y=5
After swaping : x=5 and y=4

No comments:

Post a Comment

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...