
347 views
Swap Number in C
To swap two numbers in C, you can use a temporary variable to store one of the numbers temporarily. Here’s a C program that demonstrates how to swap two numbers:
C
#include <stdio.h>
int main() {
int num1, num2, temp;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
// Swap the numbers
temp = num1;
num1 = num2;
num2 = temp;
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
return 0;
}In this program:
- We input two integers,
num1andnum2, from the user. - We print the values of
num1andnum2before swapping. - We use a temporary variable
tempto store the value ofnum1temporarily. - We then assign the value of
num2tonum1and finally assign the value stored intemp(which was the original value ofnum1) tonum2. This effectively swaps the values of the two variables. - We print the values of
num1andnum2after swapping, showing that they have been swapped.
Compile and run the program, and you can enter two numbers to see them swapped.