TExcelTAD
Home › C › C Exercises

C Exercises

Time to practise. Each exercise below has a starter playground that already compiles and runs — the missing parts are marked with TODO. Edit the code, press ▶ Run, and compare your output with the expected result. If you get stuck, open the solution, but try on your own first: struggling a little is how the knowledge sticks.

Tip: The output block under each starter shows what the unfinished starter prints. The task description tells you what the finished program should print.

Exercise 1: Temperature table

Print a conversion table from Celsius to Fahrenheit for 0, 10, 20, …, 100 °C, using a for loop and the formula F = C * 9 / 5 + 32. Each line should look like 30 C = 86.0 F.

c · try it yourself
#include <stdio.h>

int main(void) {
    printf("Celsius to Fahrenheit\n");
    // TODO: loop from 0 to 100 in steps of 10 and print each conversion
    return 0;
}
Celsius to Fahrenheit
Show solution
c
#include <stdio.h>

int main(void) {
    printf("Celsius to Fahrenheit\n");
    for (int c = 0; c <= 100; c += 10) {
        double f = c * 9.0 / 5.0 + 32.0;
        printf("%4d C = %6.1f F\n", c, f);
    }
    return 0;
}

Using 9.0 instead of 9 keeps the calculation in floating point, so values like 50 °C give exactly 122.0 °F and nothing is lost to integer division.

Exercise 2: FizzBuzz

For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number itself otherwise.

c · try it yourself
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 15; i++) {
        // TODO: print Fizz, Buzz, FizzBuzz or the number
        printf("%d\n", i);
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Show solution
c
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 15; i++) {
        if (i % 15 == 0) {
            printf("FizzBuzz\n");
        } else if (i % 3 == 0) {
            printf("Fizz\n");
        } else if (i % 5 == 0) {
            printf("Buzz\n");
        } else {
            printf("%d\n", i);
        }
    }
    return 0;
}

The i % 15 check must come first; otherwise 15 would already be caught by the i % 3 branch.

Exercise 3: Array statistics

Given the array of exam marks, compute and print the minimum, the maximum and the average (with one decimal). Expected: min 48, max 97, average 74.6.

c · try it yourself
#include <stdio.h>

int main(void) {
    int marks[] = {72, 48, 91, 66, 97, 80, 58, 85};
    int n = sizeof(marks) / sizeof(marks[0]);
    int min = 0, max = 0;
    double average = 0.0;

    // TODO: compute min, max and average

    printf("min %d, max %d, average %.1f\n", min, max, average);
    return 0;
}
min 0, max 0, average 0.0
Show solution
c
#include <stdio.h>

int main(void) {
    int marks[] = {72, 48, 91, 66, 97, 80, 58, 85};
    int n = sizeof(marks) / sizeof(marks[0]);
    int min = marks[0], max = marks[0];
    int sum = 0;

    for (int i = 0; i < n; i++) {
        if (marks[i] < min) min = marks[i];
        if (marks[i] > max) max = marks[i];
        sum += marks[i];
    }
    double average = (double) sum / n;

    printf("min %d, max %d, average %.1f\n", min, max, average);
    return 0;
}

Start min and max at the first element rather than 0 — starting min at 0 would never find anything smaller.

Exercise 4: Reverse a string in place

Write void reverse(char *s) that reverses a string without using a second array. "stressed" should become "desserts".

c · try it yourself
#include <stdio.h>
#include <string.h>

void reverse(char *s) {
    // TODO: swap characters from both ends towards the middle
    (void) s;
}

int main(void) {
    char word[] = "stressed";
    reverse(word);
    printf("%s\n", word);
    return 0;
}
stressed
Show solution
c
#include <stdio.h>
#include <string.h>

void reverse(char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len / 2; i++) {
        char tmp = s[i];
        s[i] = s[len - 1 - i];
        s[len - 1 - i] = tmp;
    }
}

int main(void) {
    char word[] = "stressed";
    reverse(word);
    printf("%s\n", word);
    return 0;
}

Only half of the string needs to be visited: each swap places two characters at once. The array word must be modifiable — reversing a string literal through a char * would be undefined behaviour.

Exercise 5: Count words

Write int count_words(const char *text) that counts words separated by one or more spaces. " C is small but mighty " contains 5 words.

c · try it yourself
#include <stdio.h>

int count_words(const char *text) {
    int words = 0;
    // TODO: count transitions from a space (or the start) to a non-space character
    (void) text;
    return words;
}

int main(void) {
    printf("%d\n", count_words("  C is   small but  mighty "));
    printf("%d\n", count_words("one"));
    printf("%d\n", count_words(""));
    return 0;
}
0
0
0
Show solution
c
#include <stdio.h>
#include <stdbool.h>

int count_words(const char *text) {
    int words = 0;
    bool in_word = false;
    for (int i = 0; text[i] != '\0'; i++) {
        if (text[i] == ' ') {
            in_word = false;
        } else if (!in_word) {
            in_word = true;     // a new word starts here
            words++;
        }
    }
    return words;
}

int main(void) {
    printf("%d\n", count_words("  C is   small but  mighty "));   // 5
    printf("%d\n", count_words("one"));                            // 1
    printf("%d\n", count_words(""));                               // 0
    return 0;
}

Counting word starts instead of spaces handles leading, trailing and repeated spaces automatically.

Exercise 6: Swap with pointers and return two results

  1. Complete swap so that it exchanges the values of two int variables.
  2. Complete min_max so that it stores the smallest and largest array element through the two pointer parameters.

Expected output: a=9 b=4 and min=-3 max=12.

c · try it yourself
#include <stdio.h>

void swap(int *a, int *b) {
    // TODO
    (void) a; (void) b;
}

void min_max(const int *v, int n, int *min, int *max) {
    // TODO
    (void) v; (void) n;
    *min = 0;
    *max = 0;
}

int main(void) {
    int a = 4, b = 9;
    swap(&a, &b);
    printf("a=%d b=%d\n", a, b);

    int values[] = {5, -3, 12, 0, 7};
    int lo, hi;
    min_max(values, 5, &lo, &hi);
    printf("min=%d max=%d\n", lo, hi);
    return 0;
}
a=4 b=9
min=0 max=0
Show solution
c
#include <stdio.h>

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

void min_max(const int *v, int n, int *min, int *max) {
    *min = v[0];
    *max = v[0];
    for (int i = 1; i < n; i++) {
        if (v[i] < *min) *min = v[i];
        if (v[i] > *max) *max = v[i];
    }
}

int main(void) {
    int a = 4, b = 9;
    swap(&a, &b);
    printf("a=%d b=%d\n", a, b);

    int values[] = {5, -3, 12, 0, 7};
    int lo, hi;
    min_max(values, 5, &lo, &hi);
    printf("min=%d max=%d\n", lo, hi);
    return 0;
}

Exercise 7: Prime numbers with a function

Write bool is_prime(int n) and use it to print all primes below 50 on one line. Expected: Primes below 50: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47.

c · try it yourself
#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
    // TODO: return true only for primes
    (void) n;
    return false;
}

int main(void) {
    printf("Primes below 50: ");
    for (int n = 2; n < 50; n++) {
        if (is_prime(n)) printf("%d ", n);
    }
    printf("\n");
    return 0;
}
Primes below 50:
Show solution
c
#include <stdio.h>
#include <stdbool.h>

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

int main(void) {
    printf("Primes below 50: ");
    for (int n = 2; n < 50; n++) {
        if (is_prime(n)) printf("%d ", n);
    }
    printf("\n");
    return 0;
}

Checking divisors only up to √n (written d * d <= n to avoid the math library) is enough: if n had a divisor larger than √n, it would also have one smaller than √n.

Exercise 8: Structs — find the best seller

Using the Book struct, find and print the title of the book with the most sales and the total sales of all books. Expected: Best seller: Dune (88 sold) and Total sold: 213.

c · try it yourself
#include <stdio.h>

typedef struct {
    const char *title;
    int sold;
} Book;

int main(void) {
    Book books[] = {
        {"Emma", 41},
        {"Dune", 88},
        {"Ulysses", 17},
        {"Matilda", 67},
    };
    int n = sizeof(books) / sizeof(books[0]);

    // TODO: find the index of the best seller and the total
    int best = 0, total = 0;
    (void) n;

    printf("Best seller: %s (%d sold)\n", books[best].title, books[best].sold);
    printf("Total sold: %d\n", total);
    return 0;
}
Best seller: Emma (41 sold)
Total sold: 0
Show solution
c
#include <stdio.h>

typedef struct {
    const char *title;
    int sold;
} Book;

int main(void) {
    Book books[] = {
        {"Emma", 41},
        {"Dune", 88},
        {"Ulysses", 17},
        {"Matilda", 67},
    };
    int n = sizeof(books) / sizeof(books[0]);

    int best = 0, total = 0;
    for (int i = 0; i < n; i++) {
        total += books[i].sold;
        if (books[i].sold > books[best].sold) best = i;
    }

    printf("Best seller: %s (%d sold)\n", books[best].title, books[best].sold);
    printf("Total sold: %d\n", total);
    return 0;
}

Remembering the index of the best element (instead of copying the struct) is cheap and gives access to every field.

Exercise 9: Dynamic array of squares

Ask malloc for an array of n ints, fill it with the squares 1, 4, 9, …, print them, and free the memory. With n = 8 the output is 1 4 9 16 25 36 49 64.

c · try it yourself
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 8;
    int *squares = NULL;
    // TODO: allocate, check for NULL, fill, print, free
    printf("allocated: %s\n", squares ? "yes" : "no");
    return 0;
}
allocated: no
Show solution
c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 8;
    int *squares = malloc(n * sizeof *squares);
    if (squares == NULL) {
        printf("out of memory\n");
        return 1;
    }
    for (int i = 0; i < n; i++) {
        squares[i] = (i + 1) * (i + 1);
    }
    for (int i = 0; i < n; i++) {
        printf("%d ", squares[i]);
    }
    printf("\n");
    free(squares);
    return 0;
}

Exercise 10: Recursive digit sum

Write a recursive function int digit_sum(int n) that returns the sum of the decimal digits of a non-negative number. digit_sum(9045) is 18.

c · try it yourself
#include <stdio.h>

int digit_sum(int n) {
    // TODO: base case for a single digit, otherwise last digit + digit_sum(rest)
    return n;
}

int main(void) {
    printf("%d\n", digit_sum(9045));
    printf("%d\n", digit_sum(7));
    return 0;
}
9045
7
Show solution
c
#include <stdio.h>

int digit_sum(int n) {
    if (n < 10) {
        return n;                     // base case: one digit
    }
    return n % 10 + digit_sum(n / 10);
}

int main(void) {
    printf("%d\n", digit_sum(9045));  // 18
    printf("%d\n", digit_sum(7));     // 7
    return 0;
}

Test yourself

In FizzBuzz, why must the check for multiples of 15 come before the check for multiples of 3?

  1. 15 is larger
  2. Otherwise 15, 30, … would match the multiple-of-3 branch first and never reach FizzBuzz
  3. The % operator only works in that order
  4. It does not matter

When searching an array for its minimum, what is the best starting value for min?

  1. 0
  2. -1
  3. The first element of the array
  4. INT_MIN

Why does is_prime loop while d * d <= n instead of d < n?

  1. It is required by C
  2. Any divisor larger than √n pairs with one smaller than √n, so checking up to √n is enough
  3. To avoid integer overflow
  4. Because primes are odd