Skip to the task
Layout
Back to classic view

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

CREATETask 4 of 20 · step 3: Strings in a programStrings with fixed text
Strings with fixed text in practice/08/

Your own strlen (length), to_upper with toupper, sizeof and strlen, snprintf with cutting, strchr and strcmp.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.
  • A multi-file program: .h files with Doxygen comments and their own CMake target.
  • Input only through the safe functions of your own input.h.
Details & hint
  • length walks up to '\0': while (s[n] != '\0').
  • toupper((unsigned char)s[i]) leaves Lithuanian letters alone.
  • snprintf returns how many characters were needed, even when they didn't fit.
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;
}