Write a function swap() that swaps two integers using pointers, and call it from main().
Solution
main.c
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int a = 10, b = 20;
printf("Before: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After: a = %d, b = %d\n", a, b);
return 0;
}
Output Verified by compiling and running
Before: a = 10, b = 20
After: a = 20, b = 10
The function receives the addresses of a and b, so writing through *a and *b changes the caller's variables. A swap that takes plain ints would only swap its own copies.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!