Swapping two numbers program in c
What is Swapping
In programming, "swapping" refers to the act of exchanging the values of two variables. This is often done as part of an algorithm or process that requires the values of the variables to be exchanged in some way.
For example, you might want to swap the values of two variables in order to sort them in ascending or descending order. Or you might want to swap the values of two variables in order to perform some other operation on them.
Swapping the values of two variables typically involves using a temporary variable to store the value of one of the variables while the values are being exchanged. This is because most programming languages do not allow you to directly exchange the values of two variables in a single operation.
Here is a simple program in C that swaps the values of two variables:
Method 1:
Swapping two numbers program in c |
#include <stdio.h>
int main() {
This program declares two integer variables a
and b
, and assigns them the values 5
and 10
respectively. It then swaps the values of a
and b
using a temporary variable temp
. Finally, it prints the values of a
and b
after the swap to confirm that the values have been swapped.
When this program is run, it will output the following:
Output:
it's gives the output:
Before swapping: a = 5, b = 10
Swapping the values of two variables and the values taking by user input
temp
. Finally, it prints out the swapped numbers.Method 2:
This program works by using the fact that the sum of two numbers is equal to the difference of the same two numbers, when one number is subtracted from the other.
To run the program, you will need to compile it using a C compiler and then run the resulting executable.