Write a C program to swap the values of two variables using a third variable
Description: Take two numbers as input and swap their values using a third variable.
Hint:
- Save the first value in a temporary variable, then copy the second into the first, and last put the temporary value in the second.
C program to swap two numbers using a third variable
#include <stdio.h>
int main(void) {
int a, b, temp;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Output:
Output of the above program is
Enter two numbers: 10 20
After swapping: a = 20, b = 10
How it works
temp = asaves 10,a = bmakes a = 20, andb = tempmakes b = 10.- Without
tempthe first value would be lost.
Learn more about the similar topics:
| Tutorials |
|---|
| C Keywords |
| C Variables |
| C Data Types |
| C Constants |
| C printf and scanf |
| C Escape Sequences |
| C Format Specifiers |