Complete the function swap so that it swaps the two numbers in main, then print them.
What to build
A function that changes two variables in main.
Requirements
- Complete
swap, using pointers. - Print the two numbers after swapping.
Input
Two whole numbers x and y.
Output
y x (the two numbers after swapping, separated by a space).
Constraints
Each number fits in an int.
Example
Input:
3 8
Output:
8 3
Why it works
swap gets the addresses of the variables, so it can reach back into main's frame, which copies of the values could never do.
Examples
Example 1 · Input
3 8
Expected output
8 3
Example 2 · Input
-1 1
Expected output
1 -1
Hints
Hint 1
The function must take int *a and int *b.
Hint 2
Use a temporary: int t = *a; *a = *b; *b = t;
Hint 3
Call it as swap(&x, &y).
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main(void) {
int x, y;
scanf("%d %d", &x, &y);
swap(&x, &y);
printf("%d %d\n", x, y);
return 0;
}