C-programming - Swapping of numbers in c, C program to swap 2 numbers
Swapping of numbers in c
This C program is to swap two numbers with and without using third variable. Swapping is used in sorting process to arrange the numbers in particular order.SWAPPING USING TEMPORAL VARIABLE
#include<stdio.h> #include<conio.h> 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(); return 0; }
In this program a temporal variable named temp is used. Here, value of first variable is copied to temp and value of second variable was copied to first and value of temp is copied to second variable. Thus the values of 2 variables are swapped.
output
Enter the value of x and y 2 3 Before Swapping x=2 y=3 After Swapping x=3 y=2
SWAPPING WITHOUT USING TEMPORAL VARIABLE
#include<stdio.h> #include<conio.h> main() { int a, b; printf("Enter two numbers to swap "); scanf("%d%d",&a,&b); printf("before swapping\na=%d\nb=%d,a,b); a = a + b; b = a - b; a = a - b; printf("after swapping\na = %d\nb = %d\n",a,b); return 0; }
output
Enter two numbers to swap 2 3 before swapping a=2 b=3 after swapping a=3 b=2
The topic on C-programming - Swapping of numbers in c is posted by - Shree
Hope you have enjoyed, C-programming - Swapping of numbers in cThanks for your time