In this tutorial, we are going to learn about Swapping of two numbers in C Language
For Examples,
Input : x = 30, y = 44 Output : x = 44, y = 30
Input: x = 500,y = 250 Output: x =250,y = 500
Input : x = 2000, y = 1000 Output : x = 1000, y = 2000
The logic used in this program is explained step by step as follows:
Step 1: Assign the value of x variable into Temporary variable : temp = x
Step 2: Assign y variable to x variable : x = y
Step 3: Assign a temporary variable to y variable: y = temp
Let us we try to understand with an example(kitchen Rule)
We have three glasses and their name is A, B and C
We have A and B glasses are filled with milk and C is empty
If we put A glass of milk in C glass (empty glass ). That we put a B glass of milk in A and then again we put a C glass of milk in B glass.
Therefore swapping A glass and B glass of Milk
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <stdio.h> int main() { int x,y ; printf("Enter the value of x : "); scanf("%d", &x); printf("\nEnter the value of y : "); scanf("%d",&y); printf("----------------------------------\n"); //Printing both numbers before swapping printf("Before swapping :x=%d y=%d",x,y); //Logic to swap two numbers int temp = x; x = y; y = temp; //Printing both numbers after swapping printf("\nAfter swapping :x=%d y=%d",x,y); } |
The output of the above program:
1 2 3 4 5 |
Enter the value of x : 20 Enter the value of y : 30 ---------------------------------- Before swapping :x=20 y=30 After swapping :x=30 y=20 |
In this tutorial, we have learned about the Swapping of two numbers in C Language by using a temporary variable.
You May Also Like:
Swapping two number using a bitwise operator in C language
Thank you for visiting.
If you have any feedback or suggestion please drop in below the comment box.