Swaps the values of two variables in c programming
How to Swap the Values of Two Variables in C
Swapping the values of two variables is a basic programming task that helps in understanding the concept of temporary storage and variable assignment. Below is a simple C program that demonstrates how to swap the values of two variables.
Example Program
#include <stdio.h>
int main() {
int a, b, temp;
// Initialize variables
a = 5;
b = 10;
// Print original values
printf("Before swapping:\\n");
printf("a = %d, b = %d\\n", a, b);
// Swap the values
temp = a;
a = b;
b = temp;
// Print swapped values
printf("After swapping:\\n");
printf("a = %d, b = %d\\n", a, b);
return 0;
}
Explanation
This program uses a temporary variable to swap the values of a
and b
. The key steps are:
- Initialization: Variables
a
andb
are initialized with values 5 and 10, respectively. - Printing Original Values: The initial values of
a
andb
are printed. - Swapping: A temporary variable
temp
is used to hold the value ofa
whilea
is assigned the value ofb
. Then,b
is assigned the value stored intemp
. - Printing Swapped Values: The values of
a
andb
after swapping are printed.
Output
When you run this program, it will display:
Before swapping:
a = 5, b = 10
After swapping:
a = 10, b = 5
Note: This method of swapping is straightforward and uses an additional variable to temporarily hold one of the values. It's a common technique for beginners to understand how variables can be reassigned.
Comments
Post a Comment