Swapping means exchanging the values stored in two variables. The clearest approach uses a temporary variable because it is easy to read and works without arithmetic-overflow concerns.
#include <stdio.h>
int main(void) {
int first = 10;
int second = 20;
int temp = first;
first = second;
second = temp;
printf("first = %d, second = %d\n", first, second);
return 0;
}
Output
first = 20, second = 10
#include <stdio.h>
int main(void) {
int first;
int second;
printf("Enter two integers: ");
if (scanf("%d %d", &first, &second) != 2) {
printf("Invalid input.\n");
return 1;
}
int temp = first;
first = second;
second = temp;
printf("After swapping: %d %d\n", first, second);
return 0;
}
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int first = 5;
int second = 8;
swap(&first, &second);
printf("%d %d\n", first, second);
return 0;
}
Learn why pointers let a function modify the caller's variables.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.