C bootcamp · Lab 11

Swap with pointers

mediumPointers12 minLesson: Pointers

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Complete swap so it exchanges the values of two ints using pointers.

main reads two integers a and b, calls swap(&a, &b), and prints them. After the call, the first printed number should be the original b, then the original a.

Input. Two integers a and b.

Output. b then a, separated by a space.

Constraints

  • You must change the values through the pointers. Do not only print in reverse order inside main.

Examples

Example 1
Input
7 2
Output
2 7
Example 2
Input
0 9
Output
9 0
Hint
  1. swap receives int *a and int *b. *a is the first value.
  2. int tmp = *a; *a = *b; *b = tmp;
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

void swap(int *a, int *b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
}

int main(void) {
  int a, b;
  if (scanf("%d %d", &a, &b) == 2) {
    swap(&a, &b);
    printf("%d %d\n", a, b);
  }
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.