Yes, Let’s write a C program to swap values. This post is useful for school students and those who are learning C programming themselves.
Swapping values are not so difficult, all you have to do is store one of the value in a temp variable and then interchange the values.
See the below small snippet of how to swap two values:
1 2 3 4 |
//swap the values temp = a; a = b; b = temp; |
Now let’s write a complete C program on how to get the values and swap them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <stdio.h> int main() { int a, b, temp; printf("Original Values:\n"); //get value a printf("a: "); scanf("%d", &a); //get value b printf("b: "); scanf("%d", &b); //swap the values temp = a; a = b; b = temp; //now print the swapped values printf("\nSwapped Values:\n"); printf("a: %d\n", a); printf("b: %d\n", b); return 0; } |
The output of the above program will be:
1 2 3 4 5 6 7 |
Original Values: a: 30 b: 50 Swapped Values: a: 50 b: 30 |
Enjoy learning!