Explain it simply
Explain it simply
This lesson adds no new syntax. It gives you four tasks from the first half of the course and asks you to solve them as small functions: the four arithmetic operations, even numbers up to a limit, a letter grade from a score, and upper-casing a string. Try each one yourself before you read the solutions.
Practising C is like practising scales on a piano. The notes are easy; the point is to play them cleanly every time, including the awkward ones. Here the awkward notes are the edge cases: dividing by zero, a score of exactly 60, an empty string. A task is finished when those work too, not when the first example does.
Problem → Why → Solution
The problem: it passed the tests I tried
Here is a typical first answer to the grade task. grade(85) returns A, grade(72) returns B, grade(30) returns F, and it looks finished. But every comparison uses > where the rule says "80 or more", so a student with exactly 80 gets a B and a student with exactly 60 fails. Nothing checks the range either, so grade(150) happily returns A for a score that cannot exist.
No line here is a syntax error, so the compiler stays silent. The bugs live only at inputs nobody tried, which is why every exercise in this lesson comes with test values chosen at the boundaries.
char grade(int score) {
if (score > 80) {
return 'A';
} else if (score > 70) {
return 'B';
} else if (score > 60) {
return 'C';
}
return 'F';
}
/* grade(85) = 'A', grade(72) = 'B', grade(30) = 'F' -> looks right
grade(80) = 'B', grade(60) = 'F', grade(150) = 'A' -> all wrong */Why one happy example is not enough
Most bugs in small programs sit at the edges: the first or last value of a range, zero, an empty string, the largest int. A test value in the middle of a range passes whether the comparison is > or >=. Only values exactly on and just past each boundary tell the two apart.
Core concept: solve it, then attack your own solution
Every exercise here follows the same routine. It is worth practising as a routine, because it is the same one you will use on real bugs.
1. Write the function signature first
Decide what goes in and what comes out before writing any logic: char grade(int score) says one int in, one character out. Putting the task in a function instead of in main with scanf also means you can call it with ten test values in a loop instead of typing ten inputs.
2. List normal, boundary and invalid inputs
For a 0-100 grade the boundaries are -1, 0, 59, 60, 69, 70, 79, 80, 100 and 101. For strings they are the empty string and a single character. For division they include a zero divisor and negative numbers.
3. Predict, then run
Write down what each test should print before running it. A mismatch between your prediction and the output is either a bug in the code or a gap in your understanding of C, and both are worth finding.
4. Read every warning
Compile with -Wall -Wextra. A warning such as "format '%d' expects argument of type 'int', but argument 2 has type 'size_t'" means the program is already wrong, even if the output happens to look right.
| Expression | Result | Why |
|---|---|---|
| 17 / 5 | 3 | int / int truncates toward zero |
| -17 / 5 | -3 | truncation toward zero, not rounding down |
| -17 % 5 | -2 | the remainder takes the left operand's sign |
| -3 % 2 == 1 | false (it is -1) | so test for even with n % 2 == 0 |
| x / 0 | undefined | always check the divisor first |
| strlen("") | 0 | returns size_t: print it with %zu |
- Write the signature
- List edge and invalid inputs
- Predict each output on paper
- Run, compare, fix the first mismatch
A test value in the middle of a range proves little; the values on the edges do the real checking.
General pattern: a function plus a test table
result_type solve(input_type value); /* the task as a function */
int main(void) {
input_type tests[] = {normal, edge_low, edge_high, invalid};
size_t n = sizeof tests / sizeof tests[0];
for (size_t i = 0; i < n; i++) {
/* print tests[i] next to solve(tests[i]) */
}
return 0;
}Each task becomes one function, and main becomes a test driver: an array of chosen inputs, a loop over it, and one line of output per case. Adding a new edge case is then one more value in the array.
Four tasks, solved and tested
Each task below is a function, and main() calls it with values picked to hit the edges: a negative dividend and a zero divisor for Task 1, a limit too small to contain any even number for Task 2, every grade boundary for Task 3, and the empty string for Task 4. Instead of being read with scanf, the test values are written into the program, so every run is repeatable and needs no keyboard.
Task 1 asks you to read a and b from the user. Once arithmetic() works, that is a small addition in main: call scanf("%d %d", &a, &b) and check that it returns 2. The function itself does not change.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
/* Task 1: the four operations, refusing to divide by zero. */
void arithmetic(int a, int b) {
printf("%d + %d = %d, %d - %d = %d, %d * %d = %d, ",
a, b, a + b, a, b, a - b, a, b, a * b);
if (b == 0) {
printf("%d / %d is not allowed\n", a, b);
} else {
printf("%d / %d = %d remainder %d\n", a, b, a / b, a % b);
}
}
/* Task 2: even numbers from 1 to limit, on one line. */
void print_evens(int limit) {
int printed = 0;
for (int n = 1; n <= limit; n++) {
if (n % 2 == 0) {
if (printed > 0) {
printf(" ");
}
printf("%d", n);
printed++;
}
}
if (printed == 0) {
printf("(none)");
}
printf("\n");
}
/* Task 3: grade for a 0-100 score; '?' marks an invalid score. */
char grade(int score) {
if (score < 0 || score > 100) {
return '?';
} else if (score >= 80) {
return 'A';
} else if (score >= 70) {
return 'B';
} else if (score >= 60) {
return 'C';
} else {
return 'F';
}
}
/* Task 4: upper-case a string in place. */
void to_upper(char *text) {
size_t len = strlen(text);
for (size_t i = 0; i < len; i++) {
text[i] = (char)toupper((unsigned char)text[i]);
}
}
int main(void) {
printf("Task 1\n");
arithmetic(17, 5);
arithmetic(-17, 5);
arithmetic(8, 0);
printf("Task 2\n");
print_evens(50);
print_evens(1);
printf("Task 3\n");
int tests[] = {-1, 0, 59, 60, 69, 70, 79, 80, 100, 101};
int count = (int)(sizeof tests / sizeof tests[0]);
for (int i = 0; i < count; i++) {
printf("%d:%c%s", tests[i], grade(tests[i]), i < count - 1 ? " " : "\n");
}
printf("Task 4\n");
char words[][16] = {"hello, c!", ""};
for (int i = 0; i < 2; i++) {
printf("\"%s\" -> ", words[i]);
to_upper(words[i]);
printf("\"%s\" (%zu chars)\n", words[i], strlen(words[i]));
}
return 0;
}Code breakdown
- Guard before dividing
if (b == 0) {Dividing an int by zero is undefined behaviour in C, often a crash, so the check must come before a / b and a % b are evaluated. Printing a message is one option; returning an error code is another.
- Truncation toward zero
printf("%d / %d = %d remainder %d\n", a, b, a / b, a % b);For -17 and 5 this prints -3 remainder -2: the quotient is truncated toward zero and the remainder keeps the sign of -17. The two always satisfy (a / b) * b + a % b == a.
- Even test with %
if (n % 2 == 0) {n % 2 == 0 is true for every even n, negative ones included. With limit 1 the loop finds nothing, and the printed counter lets the function print (none) instead of an empty line.
- Boundaries in order
} else if (score >= 80) {The range check runs first, then the grades from the highest threshold down, each with >=. Because the earlier branches have already returned, score >= 70 only ever sees scores below 80.
- Cast before toupper
text[i] = (char)toupper((unsigned char)text[i]);toupper expects a value that fits in unsigned char (or EOF). On systems where char is signed, a byte above 127 would be negative, which is undefined, so the cast comes first.
- A writable string
char words[][16] = {"hello, c!", ""};Each row is a char array initialised from a literal, so to_upper may change it. Passing a string literal itself, as in to_upper("hello"), would try to modify read-only memory.
Task 1
17 + 5 = 22, 17 - 5 = 12, 17 * 5 = 85, 17 / 5 = 3 remainder 2
-17 + 5 = -12, -17 - 5 = -22, -17 * 5 = -85, -17 / 5 = -3 remainder -2
8 + 0 = 8, 8 - 0 = 8, 8 * 0 = 0, 8 / 0 is not allowed
Task 2
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
(none)
Task 3
-1:? 0:F 59:F 60:C 69:C 70:B 79:B 80:A 100:A 101:?
Task 4
"hello, c!" -> "HELLO, C!" (9 chars)
"" -> "" (0 chars)The overflow case the tasks do not mention
One division overflows even with a non-zero divisor. INT_MIN / -1 should be 2147483648, which is one more than INT_MAX for a 32-bit int, so it is undefined behaviour, and on x86 hardware it typically stops the program with an arithmetic exception. a + b and a * b can overflow too with large values: 50000 * 50000 does not fit in an int.
For the exercise, arithmetic() can stay as it is. A real program that accepts values typed by a user should check the ranges first, or compute in a wider type such as long long. The parse_int function in the mini challenge attacks the problem from the input side: it rejects numbers that would overflow before they ever enter the program.
In real projects
In real projects
These four tasks are miniature versions of code that runs everywhere. Grade boundaries are the same problem as tax brackets, shipping-cost tiers or a thermostat's temperature bands: an off-by-one between > and >= charges someone the wrong amount. Upper-casing text shows up in case-insensitive search and in normalising country or currency codes before comparing them.
Professional C projects keep tests exactly like the arrays in this lesson. A table of inputs and expected outputs, run on every build, is how teams make sure that fixing one boundary did not break another. When a bug report arrives, the usual first step is to add the failing input to the table, watch it fail, and only then fix the code, so the same bug can never return unnoticed.
Common mistakes
Common mistakes
Using > where the rule says "or more"
If 80 and above is an A, the test is score >= 80. With > a score of exactly 80 slips into the next branch. Testing only 85 and 72 never reveals it; testing 80 does.
Checking for odd numbers with n % 2 == 1
For negative numbers the remainder is negative: -3 % 2 is -1, so the test claims -3 is not odd. Use n % 2 == 0 for even and n % 2 != 0 for odd.
Printing strlen with %d
strlen returns size_t, which is unsigned and wider than int on 64-bit systems. GCC reports "format '%d' expects argument of type 'int', but argument 2 has type 'size_t'"; use %zu.
Upper-casing a string literal
char *word = "hello"; followed by word[0] = 'H'; compiles without a warning even under -Wall -Wextra, but string literals may live in read-only memory, and on a typical desktop system the program crashes with a segmentation fault. Copy the text into a char array first.
Mini challenge
Write a safe integer parser and array statistics
Write parse_int(), which turns a string into an int only when the whole string is a valid number in range, and stats(), which finds the minimum, maximum and average of an array. Feed the parser a table of tricky strings, collect the accepted values, and summarise them.
- Accept an optional + or - followed by at least one digit, and nothing else
- Reject "", "-", "12abc" and " 5", and anything outside INT_MIN..INT_MAX
- Detect overflow before it happens, without ever overflowing an int
- stats() returns 0 for an empty array instead of reading values[0]
- Sum in long long so INT_MAX plus a few small values cannot overflow
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
/* 1 = text is a whole int (optional sign, digits only, in range); 0 = not. */
int parse_int(const char *text, int *out) {
// TODO: skip one optional sign and remember whether it was '-'
// TODO: reject "" and a lone sign
// TODO: build the value digit by digit in a long long,
// rejecting non-digits and stopping once it passes the limit
}
int stats(const int values[], int n, int *min, int *max, double *avg) {
// TODO: return 0 when n == 0; otherwise fill *min, *max, *avg and return 1
}
int main(void) {
const char *inputs[] = {"42", "-17", "+8", "007", "", "-", "12abc", " 5",
"2147483647", "2147483648", "-2147483648"};
// TODO: parse each input, print the value or "rejected",
// keep the accepted values and print their statistics
// TODO: show what stats() does with an empty array
}Expected: 42, -17, 8, 7, 2147483647 and -2147483648 are accepted; "", "-", "12abc", " 5" and "2147483648" are rejected. The summary reads 6 values, min -2147483648, max 2147483647, average 6.50, followed by a line saying the empty list has nothing to summarise.
Show hint
Keep the limit as a long long: INT_MAX for positive numbers and -(long long)INT_MIN (2147483648) for negative ones. After each value = value * 10 + digit, compare with the limit; the value can never grow past about ten times the limit, so the long long itself never overflows.
Show solution
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
/* 1 = text is a whole int (optional sign, digits only, in range); 0 = not. */
int parse_int(const char *text, int *out) {
int i = 0;
int negative = 0;
if (text[i] == '+' || text[i] == '-') {
negative = (text[i] == '-');
i++;
}
if (text[i] == '\0') {
return 0; /* "" or a lone sign */
}
long long limit = negative ? -(long long)INT_MIN : INT_MAX;
long long value = 0;
for (; text[i] != '\0'; i++) {
if (!isdigit((unsigned char)text[i])) {
return 0; /* "12abc", " 5", "1.5" */
}
value = value * 10 + (text[i] - '0');
if (value > limit) {
return 0; /* stop before it can overflow */
}
}
*out = (int)(negative ? -value : value);
return 1;
}
/* 0 when n == 0 (nothing to summarise); otherwise fills the results. */
int stats(const int values[], int n, int *min, int *max, double *avg) {
if (n == 0) {
return 0;
}
long long sum = 0; /* an int sum could overflow here */
*min = values[0];
*max = values[0];
for (int i = 0; i < n; i++) {
if (values[i] < *min) {
*min = values[i];
}
if (values[i] > *max) {
*max = values[i];
}
sum += values[i];
}
*avg = (double)sum / n;
return 1;
}
int main(void) {
const char *inputs[] = {"42", "-17", "+8", "007", "", "-", "12abc", " 5",
"2147483647", "2147483648", "-2147483648"};
int count = (int)(sizeof inputs / sizeof inputs[0]);
int values[sizeof inputs / sizeof inputs[0]]; /* room for every input */
int kept = 0;
for (int i = 0; i < count; i++) {
int v;
if (parse_int(inputs[i], &v)) {
values[kept++] = v;
printf("\"%s\" -> %d\n", inputs[i], v);
} else {
printf("\"%s\" -> rejected\n", inputs[i]);
}
}
int min, max;
double avg;
if (stats(values, kept, &min, &max, &avg)) {
printf("%d values, min %d, max %d, average %.2f\n", kept, min, max, avg);
}
if (!stats(values, 0, &min, &max, &avg)) {
printf("Empty list: nothing to summarise\n");
}
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Write each task as a function so main can test it with many values
- Choose test values on and just past every boundary, plus invalid input
- In C, / truncates toward zero and % keeps the left operand's sign
- Check divisors, use >= when the rule says "or more", and print size_t with %zu
- A safe parser rejects empty text, junk and out-of-range numbers before converting
AddressSanitizer — LLVM/Clang