C program to swap two numbers with and without using third variable, swapping in c using pointer and functions(call by reference) and using bitwise XOR operator, swapping means interchanging.But,Here we do not discuss about pointer and functions(call by reference) .This topic enable for understand after learning of pointer and function.Then that will be discuss latter. 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 of two numbers using third variable
[message_box title=”Program ” color=”red”]
/* Write a program to swap 2 numbers using third variable */
/* Written by Utpal Chaudhary */
/*Student of L.D COLLEGE OF ENGINEERING,Ahmedabad-15,Gujarat */
#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();
}
[/message_box]
[message_box title=”Output” color=”red”]
Enter the value of x and y:4 5
Before Swapping
x=4
y=5
After Swapping
x=5
y=4
[/message_box]
Swapping of two numbers without using third variable
[message_box title=”Program ” color=”red”]
/* Write a program to swap 2 numbers without using third variable */
/* Written by Utpal Chaudhary */
/*Student of L.D COLLEGE OF ENGINEERING,Ahmedabad-15,Gujarat */
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b;
clrscr();
printf(“Enter two integers to swap:”);
scanf(“%d %d”, &a, &b);
a = a + b;
b = a – b;
a = a – b;
printf(“a = %d\n b = %d\n”,a,b);
getch();
}
[/message_box]
[message_box title=”Output” color=”red”]
Enter two integers to swap:4 5
a=5
b=4
[/message_box]
Swapping of two numbers using bitwise XOR
[message_box title=”Program ” color=”red”]
/* Write a program to swap 2 numbers using bitwise XOR */
/* Written by Utpal Chaudhary */
/*Student of L.D COLLEGE OF ENGINEERING,Ahmedabad-15,Gujarat */
#include <stdio.h>
#include <conio.h>
void main()
{
int x, y;
clrscr();
scanf(“%d%d”, &x, &y);
printf(“x = %d and y = %d\n”, x, y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf(“x = %d\ny = %d\n”, x, y);
getch();
}
[/message_box]
[message_box title=”Output” color=”red”]
x=2 and y=7
x=7
y=2
[/message_box]