Nanfeng

Notes on software development, code, and curious ideas

C Programming Exercise Collection, Part 2

This collection contains practice problems commonly used in introductory C courses. Rather than memorizing answers, define the input range, select a data type that cannot overflow, separate parsing from computation, and test boundary cases.

Split-number property

For a given digit count n < 8, find every n-digit integer that equals the square of the sum of its left and right parts. When n is odd, the middle digit belongs to the left part.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

static int power10(int n) {
int result = 1;
while (n-- > 0) result *= 10;
return result;
}

int main(void) {
int n, found = 0;
if (scanf("%d", &n) != 1 || n < 1 || n >= 8) return 1;

int split = power10(n / 2);
int begin = n == 1 ? 0 : power10(n - 1);
int end = power10(n);

for (int value = begin; value < end; ++value) {
int sum = value / split + value % split;
if (sum * sum == value) {
printf("%d\n", value);
found = 1;
}
}
if (!found) puts("NO FOUND");
}

Fibonacci sequence

Print the first n Fibonacci numbers. Check the requested range because fixed-width integers eventually overflow.

1
2
3
4
5
6
7
unsigned long long a = 0, b = 1;
for (int i = 0; i < n; ++i) {
printf("%llu%c", a, i + 1 == n ? '\n' : ' ');
unsigned long long next = a + b;
a = b;
b = next;
}

Transpose a matrix

For a rectangular rows × cols matrix, output matrix[row][col] as matrix[col][row]. If a second array is allowed, the core operation is:

1
2
3
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c)
transposed[c][r] = matrix[r][c];

Normalize and count text

String exercises in the collection include copying, comparison, concatenation, character conversion, word counting, and removal of selected characters. Prefer bounded input:

1
2
3
4
5
6
7
8
9
10
char line[256];
if (fgets(line, sizeof line, stdin)) {
int words = 0, inside = 0;
for (size_t i = 0; line[i] != '\0'; ++i) {
int space = line[i] == ' ' || line[i] == '\t' || line[i] == '\n';
if (!space && !inside) ++words;
inside = !space;
}
printf("%d\n", words);
}

Other exercises cover snake matrices, sorted insertion and deletion, phone books, factorial and polynomial sums, numerical approximations of e and sine, digit decomposition, Josephus-style counting, projectile rebound, and the monkey-and-peaches recurrence.

Compile with warnings enabled—for example -Wall -Wextra -Wpedantic—and add tests for zero, one, maximum input, duplicates, empty strings, and malformed input. Those habits are more valuable than any individual answer in a question bank.

+