Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 135 ยท Practice and Review

C Practice Exercises

30 graded C exercises with solutions on loops, functions, arrays, strings, pointers, malloc, structs, linked lists, bit flags and files. Run C in your browser.

You learn C by writing C. Lessons build understanding, but only practice builds the reflexes: getting a loop's bounds right the first time, remembering the null terminator, checking what malloc returned, freeing what you allocated. This page collects 30 exercises that cover the whole course, grouped by topic and ordered from beginner to advanced inside each group.

Every exercise has a short task, an editor with starter code, and a hidden solution. The starter code compiles and runs as given: the functions you need to write are stubs that return a placeholder value, and the comments in main show the output you should get once your code works. Replace the stub body, press Run, and compare.

  • Try first, peek later. Give each exercise a real attempt before you open the solution. A few minutes of being stuck is where the learning happens.
  • Compare, don't copy. Your solution can look different from ours and still be right. Read ours for ideas, then improve yours.
  • Read the warnings. Our compiler runs with -Wall -Wextra, so it points out suspicious code. The stubs mark parameters [[maybe_unused]] (a C23 attribute) only so the empty versions compile without "unused parameter" warnings; delete the attribute once your code uses the parameter.
  • Test the edges. Empty strings, empty arrays, zero, negative numbers and the largest values are where C programs break. Most exercises include at least one edge case in their test calls.

Each group links to the lessons it practices. Keep the cheat sheet open in another tab, and look at the 50 classic programs if you want worked examples first.

Basics and control flow

These practice printf, reading input, if statements, for loops and while loops.

1. Times table (Beginner)

Read one whole number from the Input box and print its times table from 1 to 10, using the exact format in the comment (%d x %2d = %3d).

C Exercise 1: Times table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
for (int i = 1; i <= 10; i++) {
    printf("%d x %2d = %3d\n", n, i, n * i);
}

The field widths %2d and %3d pad with spaces, so the = signs and the results line up in columns.

2. Clap-Snap (Beginner)

For the numbers 1 to 21, print Clap for multiples of 3, Snap for multiples of 7, ClapSnap for multiples of both, and the number itself otherwise. Print everything on one line, separated by spaces.

C Exercise 2: Clap-Snap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
for (int n = 1; n <= 21; n++) {
    bool clap = n % 3 == 0;
    bool snap = n % 7 == 0;
    if (clap || snap) {
        printf("%s%s ", clap ? "Clap" : "", snap ? "Snap" : "");
    } else {
        printf("%d ", n);
    }
}

Computing both conditions first means "both" needs no special case: 21 prints both words in one call. (bool is a keyword in C23; in older C, include <stdbool.h>.)

3. Letter grades (Beginner)

Write letter_grade(score) that returns 'A' for 90โ€“100, 'B' for 80โ€“89, 'C' for 70โ€“79, 'D' for 60โ€“69 and 'F' below 60. Scores outside 0โ€“100 return '?'. The program reads the scores from the Input box.

C Exercise 3: Letter grades

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
char letter_grade(int score) {
    if (score < 0 || score > 100) {
        return '?';
    }
    if (score >= 90) {
        return 'A';
    }
    if (score >= 80) {
        return 'B';
    }
    if (score >= 70) {
        return 'C';
    }
    if (score >= 60) {
        return 'D';
    }
    return 'F';
}

Rejecting invalid input first and then testing thresholds from the top down means each check only needs a lower bound.

4. Digital root (Intermediate)

Add up the digits of a number; if the result has more than one digit, repeat until one digit remains. For 98765: 9 + 8 + 7 + 6 + 5 = 35, then 3 + 5 = 8. Use % and /, not strings.

C Exercise 4: Digital root

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
int digital_root(unsigned long long number) {
    while (number >= 10) {
        unsigned long long sum = 0;
        for (; number > 0; number /= 10) {
            sum += number % 10;
        }
        number = sum;
    }
    return (int)number;
}

The outer loop repeats while there is more than one digit, and the inner loop peels digits off with % 10 and / 10. (For positive numbers there's also a formula: 1 + (n - 1) % 9.)

Functions and recursion

These practice functions, parameters and return values and recursion.

5. Counting primes (Beginner)

Write count_primes(limit) that returns how many primes are below limit. A helper is_prime function makes it easy to read; a sieve makes it fast.

C Exercise 5: Counting primes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
bool is_prime(int n) {
    if (n < 2) {
        return false;
    }
    for (int d = 2; d <= n / d; d++) {
        if (n % d == 0) {
            return false;
        }
    }
    return true;
}

int count_primes(int limit) {
    int count = 0;
    for (int n = 2; n < limit; n++) {
        if (is_prime(n)) {
            count++;
        }
    }
    return count;
}

Testing divisors only while d <= n / d (the square-root bound, written so it can't overflow) keeps this fast enough for limits in the hundreds of thousands.

6. Tower of Hanoi (Intermediate)

Move disks disks from peg A to peg C using peg B, never placing a larger disk on a smaller one. Write a recursive hanoi that prints each move when print is true and returns the number of moves.

C Exercise 6: Tower of Hanoi

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
long hanoi(int disks, char from, char to, char via, bool print) {
    if (disks == 0) {
        return 0;
    }
    long moves = hanoi(disks - 1, from, via, to, print);
    if (print) {
        printf("Move disk %d from %c to %c\n", disks, from, to);
    }
    moves++;
    moves += hanoi(disks - 1, via, to, from, print);
    return moves;
}

To move n disks, move n โˆ’ 1 out of the way, move the largest, then move the n โˆ’ 1 back on top. That gives 2โฟ โˆ’ 1 moves.

7. Print binary recursively (Intermediate)

Write print_binary(n) that prints n in binary without an array or string: recursion prints the higher bits first, then the last bit n % 2.

C Exercise 7: Binary with recursion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
void print_binary(unsigned n) {
    if (n >= 2) {
        print_binary(n / 2);
    }
    putchar('0' + (int)(n % 2));
}

Recursing before printing reverses the order: the deepest call prints the most significant bit first. Stopping at n >= 2 (not n > 0) makes 0 print as 0 instead of nothing.

8. Integer square root (Intermediate)

Write isqrt(n) that returns the largest whole number r with r * r <= n, without <math.h>. Use binary search over the possible answers, and watch out for overflow near UINT_MAX.

C Exercise 8: Integer square root

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
unsigned isqrt(unsigned n) {
    unsigned low = 0;
    unsigned high = n < 65535u ? n : 65535u;   // sqrt(UINT_MAX) < 65536
    while (low < high) {
        unsigned middle = low + (high - low + 1) / 2;   // round up
        if (middle <= n / middle) {
            low = middle;          // middle * middle <= n
        } else {
            high = middle - 1;
        }
    }
    return low;
}

middle <= n / middle tests middle * middle <= n without multiplying, so it can't overflow. Rounding the midpoint up guarantees the range shrinks when low = middle.

Arrays

These practice arrays, multidimensional arrays and pointers and arrays.

9. Reverse an array in place (Beginner)

Write reverse_array(values, count) that reverses the elements without a second array. It must also work for 0 and 1 elements.

C Exercise 9: Reverse an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
void reverse_array(int *values, size_t count) {
    for (size_t i = 0; i < count / 2; i++) {
        int temp = values[i];
        values[i] = values[count - 1 - i];
        values[count - 1 - i] = temp;
    }
}

Looping to count / 2 swaps each pair once. For count == 0 the loop never runs, so count - 1 (which would wrap around for size_t) is never evaluated, and the NULL pointer is never touched.

10. Running totals (Beginner)

Write running_totals(in, out, count) so that out[i] is the sum of in[0] through in[i].

C Exercise 10: Running totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
void running_totals(const int *in, int *out, size_t count) {
    int sum = 0;
    for (size_t i = 0; i < count; i++) {
        sum += in[i];
        out[i] = sum;
    }
}

One pass with an accumulator is O(n); recomputing each sum from scratch would be O(nยฒ). The const on in documents (and enforces) that the input isn't modified.

11. Move zeros to the end (Intermediate)

Move every 0 to the end of the array while keeping the other values in their original order. Do it in place, in one pass plus a fill.

C Exercise 11: Move zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
void move_zeros(int *values, size_t count) {
    size_t write = 0;
    for (size_t read = 0; read < count; read++) {
        if (values[read] != 0) {
            values[write++] = values[read];
        }
    }
    while (write < count) {
        values[write++] = 0;
    }
}

The two-index compaction copies non-zero values forward in order; whatever space is left at the end is filled with zeros.

12. Maximum subarray sum (Advanced)

Find the largest sum of any non-empty run of consecutive elements. For {-2, 1, -3, 4, -1, 2, 1, -5, 4} the best run is 4, -1, 2, 1 with sum 6. Aim for one pass (Kadane's algorithm).

C Exercise 12: Maximum subarray

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
long max_subarray_sum(const int *values, size_t count) {
    long best = values[0];
    long current = values[0];
    for (size_t i = 1; i < count; i++) {
        long extended = current + values[i];
        current = extended > values[i] ? extended : values[i];
        if (current > best) {
            best = current;
        }
    }
    return best;
}

current is the best sum of a run that ends at element i: either extend the previous run or start fresh. Starting from values[0] (not 0) gives the right answer when every value is negative.

13. Spiral order (Advanced)

Print the elements of a matrix in clockwise spiral order, starting at the top-left. Keep four boundaries (top, bottom, left, right) and shrink them after each side.

C Exercise 13: Spiral order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
void print_spiral(size_t rows, size_t cols, const int m[rows][cols]) {
    size_t top = 0, bottom = rows, left = 0, right = cols;   // half-open bounds
    while (top < bottom && left < right) {
        for (size_t j = left; j < right; j++) {
            printf("%d ", m[top][j]);
        }
        top++;
        for (size_t i = top; i < bottom; i++) {
            printf("%d ", m[i][right - 1]);
        }
        right--;
        if (top < bottom) {
            for (size_t j = right; j > left; j--) {
                printf("%d ", m[bottom - 1][j - 1]);
            }
            bottom--;
        }
        if (left < right) {
            for (size_t i = bottom; i > top; i--) {
                printf("%d ", m[i - 1][left]);
            }
            left++;
        }
    }
}

Half-open bounds keep every index a valid size_t (no -1), and the two if checks stop a single remaining row or column from being printed twice.

Strings

These practice strings, string functions, characters, safe string handling and string conversions.

14. Count words (Beginner)

Write count_words(s) that counts words separated by any whitespace (spaces, tabs, newlines), including leading, trailing and repeated whitespace.

C Exercise 14: Count words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
size_t count_words(const char *s) {
    size_t words = 0;
    bool in_word = false;
    for (; *s != '\0'; s++) {
        if (isspace((unsigned char)*s)) {
            in_word = false;
        } else if (!in_word) {
            in_word = true;
            words++;
        }
    }
    return words;
}

Counting the moments you enter a word handles any amount of whitespace anywhere. The unsigned char cast keeps isspace safe for bytes above 127.

15. Caesar cipher (Intermediate)

Write caesar(s, shift) that shifts every letter by shift positions in place, wrapping around the alphabet and keeping uppercase and lowercase. Other characters stay unchanged. Negative and large shifts must work too.

C Exercise 15: Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
void caesar(char *s, int shift) {
    int normalized = (shift % 26 + 26) % 26;   // 0..25, even for negative shifts
    for (; *s != '\0'; s++) {
        unsigned char c = (unsigned char)*s;
        if (isupper(c)) {
            *s = (char)('A' + (c - 'A' + normalized) % 26);
        } else if (islower(c)) {
            *s = (char)('a' + (c - 'a' + normalized) % 26);
        }
    }
}

In C, % of a negative number is negative (-3 % 26 == -3), so adding 26 and taking % 26 again turns any shift into the range 0โ€“25.

16. Reverse the words (Intermediate)

Reverse the order of the words in a string in place: "the quick brown fox" becomes "fox brown quick the". Words are separated by single spaces. Hint: reverse the whole string, then reverse each word.

C Exercise 16: Reverse the words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
static void reverse_range(char *first, char *last) {   // reverses [first, last)
    while (first < last) {
        last--;
        if (first == last) {
            break;
        }
        char temp = *first;
        *first = *last;
        *last = temp;
        first++;
    }
}

void reverse_words(char *s) {
    char *end = s + strlen(s);
    reverse_range(s, end);
    char *word = s;
    while (word < end) {
        char *space = strchr(word, ' ');
        char *word_end = space != NULL ? space : end;
        reverse_range(word, word_end);
        word = word_end + 1;
    }
}

After reversing everything, the words are in the right order but each one is spelled backwards; reversing each word fixes the spelling. No extra buffer is needed.

17. Longest common prefix (Intermediate)

Write common_prefix_length(words, count) that returns the length of the longest prefix shared by all the strings. main prints the prefix with %.*s, which prints only that many characters.

C Exercise 17: Longest common prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
size_t common_prefix_length(const char *words[], size_t count) {
    if (count == 0) {
        return 0;
    }
    size_t length = 0;
    for (;;) {
        char c = words[0][length];
        if (c == '\0') {
            return length;
        }
        for (size_t i = 1; i < count; i++) {
            if (words[i][length] != c) {
                return length;
            }
        }
        length++;
    }
}

Compare column by column. A shorter word stops the scan automatically: its '\0' never equals the other word's letter.

18. Join words safely (Intermediate)

Write join_words that writes the words separated by separator into out (of size bytes). It returns true on success and false if the result doesn't fit. Never write past out + size. snprintf is the easiest tool.

C Exercise 18: Join words safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
bool join_words(const char *words[], size_t count, const char *separator,
                char *out, size_t size) {
    if (size == 0) {
        return false;
    }
    out[0] = '\0';
    size_t used = 0;
    for (size_t i = 0; i < count; i++) {
        int written = snprintf(out + used, size - used, "%s%s",
                               i == 0 ? "" : separator, words[i]);
        if (written < 0 || (size_t)written >= size - used) {
            return false;
        }
        used += (size_t)written;
    }
    return true;
}

snprintf returns the length it wanted to write; if that's at least the space left, the output was truncated. Tracking used avoids calling strlen again and again, which strcat in a loop would do.

19. Parse integers safely (Intermediate)

Write parse_int(text, &result) that accepts optional leading spaces, a sign and digits (trailing spaces are fine), and rejects empty strings, trailing junk and values outside the int range. Use strtol, its end pointer and errno.

C Exercise 19: Parse integers safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
bool parse_int(const char *text, int *result) {
    char *end = NULL;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (end == text) {
        return false;                       // no digits at all
    }
    while (isspace((unsigned char)*end)) {
        end++;
    }
    if (*end != '\0') {
        return false;                       // junk after the number
    }
    if (errno == ERANGE || value < INT_MIN || value > INT_MAX) {
        return false;                       // doesn't fit in long or int
    }
    *result = (int)value;
    return true;
}

strtol reports three different failures in three different places: end == text (nothing parsed), *end (leftovers) and errno == ERANGE (overflow). atoi reports none of them, which is why you should avoid it.

Pointers

These practice pointers, pointers and functions, const and pointers and void pointers.

20. Minimum and maximum through out-parameters (Beginner)

Write min_max that stores the smallest and largest value through two pointer parameters and returns false (storing nothing) for an empty array.

C Exercise 20: Out-parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
bool min_max(const int *values, size_t count, int *min_out, int *max_out) {
    if (count == 0) {
        return false;
    }
    int low = values[0];
    int high = values[0];
    for (size_t i = 1; i < count; i++) {
        if (values[i] < low) {
            low = values[i];
        }
        if (values[i] > high) {
            high = values[i];
        }
    }
    *min_out = low;
    *max_out = high;
    return true;
}

Returning a success flag and writing results through pointers is the standard C way to return several values. Writing only on success means the caller's variables are untouched on failure.

21. Write your own strchr (Intermediate)

Write find_char(s, c) that returns a pointer to the first occurrence of c in s, or NULL if there is none. Like the real strchr, searching for '\0' returns a pointer to the terminator.

C Exercise 21: Your own strchr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
char *find_char(const char *s, int c) {
    char target = (char)c;
    for (;; s++) {
        if (*s == target) {
            return (char *)s;
        }
        if (*s == '\0') {
            return NULL;
        }
    }
}

Checking for the target before the terminator makes '\0' findable. The cast removes const exactly as the standard strchr does, so one function serves both const and non-const strings (C23 adds type-generic versions that keep the const).

22. A generic swap (Intermediate)

Write swap_any(a, b, size) that swaps two objects of any type, given their addresses and size. void * can't be dereferenced, so work through unsigned char * byte by byte (or use memcpy with a buffer).

C Exercise 22: Generic swap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
void swap_any(void *a, void *b, size_t size) {
    unsigned char *left = a;
    unsigned char *right = b;
    for (size_t i = 0; i < size; i++) {
        unsigned char temp = left[i];
        left[i] = right[i];
        right[i] = temp;
    }
}

In C, void * converts to any object pointer without a cast. Swapping bytes works for every type because every object is a sequence of size bytes; this is how qsort moves elements it knows nothing about.

Dynamic memory

These practice malloc, calloc, realloc and free, memory errors and building a dynamic array.

23. Duplicate a string (Beginner)

Write duplicate(s) that returns a new heap copy of s (the caller frees it), or NULL if allocation fails. Remember the byte for the terminator. (C23 adds strdup to the standard library; writing it yourself is a classic exercise.)

C Exercise 23: Duplicate a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
char *duplicate(const char *s) {
    size_t size = strlen(s) + 1;   // + 1 for '\0'
    char *copy = malloc(size);
    if (copy == NULL) {
        return NULL;
    }
    memcpy(copy, s, size);
    return copy;
}

memcpy copies the terminator along with the characters because size includes it. Forgetting the + 1 is a classic one-byte heap overflow.

24. Read any number of values (Intermediate)

Write read_all(&count) that reads integers from standard input until there are no more, storing them in a heap array that grows with realloc (double the capacity when it's full). Return the array and store the number of values in *count_out.

C Exercise 24: A growing array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
int *read_all(size_t *count_out) {
    size_t capacity = 4;
    size_t count = 0;
    int *values = malloc(capacity * sizeof *values);
    if (values == NULL) {
        *count_out = 0;
        return NULL;
    }
    int number = 0;
    while (scanf("%d", &number) == 1) {
        if (count == capacity) {
            int *bigger = realloc(values, 2 * capacity * sizeof *values);
            if (bigger == NULL) {
                break;   // keep what we have
            }
            values = bigger;
            capacity *= 2;
        }
        values[count++] = number;
    }
    *count_out = count;
    return values;
}

Assigning realloc's result to a temporary first matters: if it fails it returns NULL but leaves the old block allocated, and values = realloc(values, ...) would lose your only pointer to it.

25. Split a string into words (Advanced)

Write split_words(text, &count) that returns a heap array of heap-allocated copies of each word in text (words are separated by spaces). The caller frees everything with free_words, which is provided. On any allocation failure, free whatever you allocated and return NULL.

C Exercise 25: Split into words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
char **split_words(const char *text, size_t *count_out) {
    *count_out = 0;
    size_t capacity = 0;
    for (const char *p = text; *p != '\0'; p++) {   // count words first
        if (*p != ' ' && (p == text || p[-1] == ' ')) {
            capacity++;
        }
    }
    char **words = malloc((capacity > 0 ? capacity : 1) * sizeof *words);
    if (words == NULL) {
        return NULL;
    }
    size_t count = 0;
    const char *p = text;
    while (*p != '\0') {
        p += strspn(p, " ");                 // skip spaces
        size_t length = strcspn(p, " ");     // length of the word
        if (length == 0) {
            break;
        }
        char *word = malloc(length + 1);
        if (word == NULL) {
            free_words(words, count);
            return NULL;
        }
        memcpy(word, p, length);
        word[length] = '\0';
        words[count++] = word;
        p += length;
    }
    *count_out = count;
    return words;
}

Counting first means one exact allocation for the pointer array. strspn and strcspn measure runs of "these characters" and "anything but these", which makes tokenizing clean without modifying the input (unlike strtok). Allocating at least one slot avoids malloc(0), whose result may be NULL.

Structures and data structures

These practice structures, arrays of structures, qsort, linked lists and stacks and queues.

26. Sort students (Intermediate)

Write the qsort comparator so students are sorted by grade from highest to lowest, and students with the same grade alphabetically by name.

C Exercise 26: Sort students

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
int compare_students(const void *a, const void *b) {
    const Student *left = a;
    const Student *right = b;
    if (left->grade != right->grade) {
        return (right->grade > left->grade) - (right->grade < left->grade);   // descending
    }
    return strcmp(left->name, right->name);                                  // ascending
}

Compare the primary key first and fall back to the secondary key only on a tie. Swapping left and right in the first comparison reverses the order. qsort isn't stable, so the tie-breaker is what makes the order predictable.

27. Reverse a linked list (Advanced)

The starter builds the list 5 -> 4 -> 3 -> 2 -> 1 with push_front. Write reverse_list(head) that reverses the links in place and returns the new head. No new nodes, no arrays.

C Exercise 27: Reverse a linked list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
Node *reverse_list(Node *head) {
    Node *previous = NULL;
    while (head != NULL) {
        Node *next = head->next;   // remember the rest
        head->next = previous;     // turn this link around
        previous = head;
        head = next;
    }
    return previous;
}

Three pointers walk the list once: previous is the already reversed part, head the current node, next the rest. Saving next before changing head->next is the step people forget.

28. Balanced brackets (Intermediate)

Write is_balanced(s) that checks whether every (, [ and { is closed by the matching bracket in the right order. Other characters are ignored. Use an array as a stack (100 levels is plenty; report deeper nesting as unbalanced).

C Exercise 28: Balanced brackets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
bool is_balanced(const char *s) {
    char stack[100];
    size_t depth = 0;
    for (; *s != '\0'; s++) {
        char c = *s;
        if (c == '(' || c == '[' || c == '{') {
            if (depth == sizeof stack) {
                return false;   // too deep
            }
            stack[depth++] = c;
        } else if (c == ')' || c == ']' || c == '}') {
            char expected = c == ')' ? '(' : c == ']' ? '[' : '{';
            if (depth == 0 || stack[depth - 1] != expected) {
                return false;
            }
            depth--;
        }
    }
    return depth == 0;
}

Every closer must match the most recent unmatched opener, which is exactly what a stack's top holds. At the end, the stack must be empty, or some opener was never closed.

Bits and files

These practice bitwise operators, enumerations, file handling and text files.

29. Permission flags (Intermediate)

Each permission is one bit. Write grant (set bits), revoke (clear bits), toggle (flip bits) and describe, which writes a three-letter string like r-x into out.

C Exercise 29: Permission flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
unsigned grant(unsigned perms, unsigned flags) { return perms | flags; }
unsigned revoke(unsigned perms, unsigned flags) { return perms & ~flags; }
unsigned toggle(unsigned perms, unsigned flags) { return perms ^ flags; }

void describe(unsigned perms, char out[4]) {
    out[0] = (perms & PERM_READ) ? 'r' : '-';
    out[1] = (perms & PERM_WRITE) ? 'w' : '-';
    out[2] = (perms & PERM_EXEC) ? 'x' : '-';
    out[3] = '\0';
}

| sets, & ~ clears, ^ flips and & tests. Combining flags with | (as in PERM_READ | PERM_WRITE) lets one call change several bits at once.

30. Write and read back a file (Intermediate)

Write write_squares(path, count) that writes the squares of 1 to count to a text file, one per line, and sum_file(path) that reads the numbers back and returns their sum (or -1 if the file can't be opened). Check every fopen and close every file. (Files in our editor exist only while the program runs.)

C Exercise 30: File round trip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Show solution
C
bool write_squares(const char *path, int count) {
    FILE *file = fopen(path, "w");
    if (file == NULL) {
        return false;
    }
    for (int i = 1; i <= count; i++) {
        fprintf(file, "%d\n", i * i);
    }
    return fclose(file) == 0;   // fclose flushes; it can fail too
}

long sum_file(const char *path) {
    FILE *file = fopen(path, "r");
    if (file == NULL) {
        return -1;
    }
    long sum = 0;
    long number = 0;
    while (fscanf(file, "%ld", &number) == 1) {
        sum += number;
    }
    fclose(file);
    return sum;
}

Checking fclose when writing catches errors that only show up when buffered data is finally written (a full disk, for example). Reading loops on fscanf(...) == 1, never on feof.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 24, why is values = realloc(values, new_size) a bug?

    On failure realloc leaves the old block allocated and returns NULL. Assign to a temporary, check it, then update the original pointer.
  2. 2. What does -3 % 26 evaluate to in C, which is why exercise 15 normalizes the shift?

    The remainder takes the sign of the left operand, so -3 % 26 is -3. Adding 26 and taking % 26 again maps it to 23.
  3. 3. A loop is written for (size_t i = count - 1; i >= 0; i--). What happens?

    size_t is unsigned, so i >= 0 is always true and decrementing 0 wraps to the largest value, causing out-of-bounds reads. GCC warns with -Wextra (comparison is always true).
  4. 4. Why does exercise 26's comparator need a tie-breaker on the name?

    qsort makes no promise about the relative order of equal elements. A secondary key makes the result fully determined.

Summary

  • The basics exercises train loops, scanf with a checked return value, and printf field widths.
  • Functions and recursion: split problems into small functions; recursive solutions need a base case and a smaller problem each step.
  • Array work is mostly index discipline: half-open ranges, count / 2 swaps, two-index compaction, and care with size_t near zero.
  • String exercises revolve around the null terminator, unsigned char casts for <ctype.h>, bounded writes with snprintf, and strtol with full error checks.
  • Pointer exercises return several results through out-parameters and write generic code with void * and bytes.
  • Memory exercises check every allocation, use a temporary for realloc, and free everything on every path.
  • Structs, linked lists and stacks combine all of it; bit flags use |, & ~, ^ and &; file code checks fopen and fclose.

Next: C Interview Questions, to practice explaining these ideas out loud.