Variable var1 contains 40 and Variable var2 contains 30
then After swapping
Variable var1 contains 30 and Variable var2 contains 40.
Also Read: Quine - Print its own Source Code as Output
Also Read: C++ Program To Implements Snake and Ladder Game ( Graphics )
Example: Suppose we have three glass X, Y, Temp. Glass X contain 50, Glass Y contain 100 and Glass Temp is empty now we want to interchange these two glass (X, Y) value. So we follow The steps...
First we take Glass X and there values place inside Glass Temp
Now Glass X is empty, take Glass Y and there values place inside Glass X.
Now Glass Y is empty, take Glass Temp and there values place inside Glass Y
Finally Both Glass values are exchange, Glass X contain 100 and Glass Y contain 50.
Swap two numbers using third variables
Source Code
#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
Swap two numbers without using third variable
Source Code
#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
Swap two numbers using Pointers
Source Code
#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();
}
OutputEnter 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
Source Code
#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
Source Code
#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

0 comments:
Post a Comment