Nanfeng

Notes on software development, code, and curious ideas

C Programming Exercise Collection, Part 1

This first exercise collection progresses from simple input and arithmetic to arrays, strings, calendar calculations, and dynamic programming. Each solution should validate input, use a sufficiently wide type, and compile without warnings.

Subtract two integers

1
2
3
4
5
6
#include <stdio.h>
int main(void) {
long long a, b;
if (scanf("%lld%lld", &a, &b) != 2) return 1;
printf("%lld\n", a - b);
}

Greatest common divisor

1
2
3
4
5
6
7
8
9
10
static long long gcd(long long a, long long b) {
if (a < 0) a = -a;
if (b < 0) b = -b;
while (b != 0) {
long long remainder = a % b;
a = b;
b = remainder;
}
return a;
}

Decode a character string

When a problem defines a fixed substitution, keep the transformation explicit and preserve characters outside the intended range:

1
2
3
4
for (size_t i = 0; text[i] != '\0'; ++i) {
if (text[i] >= 'A' && text[i] <= 'Z')
text[i] = (char)('A' + (text[i] - 'A' + shift) % 26);
}

Pascal’s triangle

1
2
3
4
5
6
triangle[0][0] = 1;
for (int row = 1; row < n; ++row) {
triangle[row][0] = triangle[row][row] = 1;
for (int col = 1; col < row; ++col)
triangle[row][col] = triangle[row - 1][col - 1] + triangle[row - 1][col];
}

The full set also includes selecting the heaviest apple, exchanging bottles, string comparison and copying, Josephus counting, weekday calculation, digit filtering and reversal, age grouping, fraction-series sums, matrix saddle points, longest words, longest increasing subsequences, day-of-year calculation, and tiered bonuses.

For every exercise, write down the invariant before coding and test minimum, maximum, duplicate, and malformed cases. Prefer fgets plus parsing for free-form text, avoid unbounded %s, and enable -Wall -Wextra -Wpedantic while learning.

+