Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: About.

CHECKTask 5 of 17 · step 2: Questions 1–6Swapping without pointers
Swapping without pointers in practice/08/

void swap(int a, int b) swaps a and b. main: x = 1, y = 2, swap(x, y), printf x y. What does it print?

Details & hint

Stuck? 1 2: the function swaps copies. You need int *a, int *b and swap(&x, &y). (Topic 8)

practice 08 pointers.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
#define N 5
/* Swaps the values of two variables.
Before: a != NULL, b != NULL. */
void swap(int *a, int *b) {
assert(a != NULL && b != NULL);
int tmp = *a;
*a = *b;
*b = tmp;
}
/* Finds the smallest and the largest value and returns them through pointers.
Before: n >= 1, t, min and max not NULL.
After: *min is the smallest, *max the largest value of t. */
void min_max(const int t[], int n, int *min, int *max) {
assert(n >= 1 && t != NULL && min != NULL && max != NULL);
*min = t[0];
*max = t[0];
for (int i = 1; i < n; i++) {
if (t[i] < *min) {
*min = t[i];
}
if (t[i] > *max) {
*max = t[i];
}
}
}
/* The sum, walking the array with a pointer.
Before: n >= 0, t != NULL. */
int sum(const int *t, int n) {
assert(n >= 0 && t != NULL);
int s = 0;
for (const int *p = t; p < t + n; p++) {
s += *p;
}
return s;
}
int main(void) {
int x = 3;
int y = 8;
printf("Before: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After: x = %d, y = %d\n", x, y);
int t[N] = {4, -2, 9, 0, 7};
int min;
int max;
min_max(t, N, &min, &max);
printf("Smallest: %d, largest: %d\n", min, max);
printf("Sum: %d\n", sum(t, N));
return 0;
}