Explain it simply
Explain it simply
This project brings variables, arrays, loops, functions, structs and if...else together in one program. It reads lines like "Aye 75", keeps only the valid ones, and prints a report with each student's result, how many passed and the class average.
Think of a small office that handles exam results. One clerk checks each form, another does the maths, and a third types up the final report. Nobody does everything, so when a number comes out wrong you know exactly which desk to visit. Our program works the same way: parse_line() checks, average() and count_passed() calculate, print_report() prints, and main() only passes work between them.
Problem → Why → Solution
The problem: everything inside main
A first attempt usually puts everything in main: ask for a score with scanf, add it to a total, divide, print. It works the first time you type three clean numbers. Then you type 75, then 8two by accident. scanf reads the 8 and leaves "two" waiting, and the third call fails at once because "two" is not a number. scores[2] was never assigned, so it holds whatever happened to be in that memory, and the total becomes garbage.
The division hides a second bug. With 75, 82 and 69 the true average is 75.33, but total / 3 divides two ints and throws the fraction away, printing 75. And because the maths sits inside the input loop, you cannot test the average without typing at the keyboard every time.
#include <stdio.h>
int main(void) {
int scores[3];
int total = 0;
for (int i = 0; i < 3; i++) {
printf("Score %d: ", i + 1);
scanf("%d", &scores[i]); /* return value ignored */
total += scores[i];
}
printf("Average: %d\n", total / 3); /* int / int drops the fraction */
if (total / 3 >= 60) {
printf("Passed\n");
}
/* grades, best student, saving to a file... all of it piles up here */
return 0;
}Why it breaks in such confusing ways
scanf returns how many values it converted, and that number is the only sign that the input was valid. Ignoring it lets a failed read leave a variable uninitialised and the bad characters stuck in the input. Mixing reading, maths and printing in one block also means every bug looks like an input bug, because there is no smaller piece you can run and check on its own.
Core concept: give each part of the program one job
A C program of any size is easier to get right when it is split along the path the data travels. For this report the data moves through four stages, and each stage becomes one or two functions with a clear contract. The contract is written in the signature: what the function receives, what it promises to return, and what it is not allowed to touch.
1. Input: turn text into a checked struct
parse_line() receives one line and a pointer to the Student it should fill. It returns 1 only when the line holds exactly a name and a number from 0 to 100. Everything else, including "Daw abc", "Ei 105" and "Aye 75 extra", returns 0, so the rest of the program never sees unchecked data.
2. Storage: a fixed array with a capacity check
Valid students go into struct Student list[MAX_STUDENTS]. Before every write, main() compares count with MAX_STUDENTS, because writing list[8] in an array of 8 would silently overwrite other memory. A fixed array is enough here; the challenge swaps it for a heap array that grows.
3. Logic: pure functions over the array
average() and count_passed() take the array as const and the count as a separate parameter, since an array parameter arrives as a pointer and does not know its own length. They never print and never read input, so you can call them with any test data and compare the results.
4. Output: one function owns the format
print_report() is the only place that decides column widths and wording, so changing the report layout never risks breaking the maths.
Why total / (double)count
If both operands are int, C performs integer division and drops the fraction: 270 / 4 is 67, not 67.5. Converting one operand to double first makes the whole division happen in floating point. The cast must go on an operand, not around the result: (double)(total / count) still gives 67.0.
- A text line comes in
- parse_line() accepts or rejects it
- A valid struct is stored if room remains
- Logic functions compute from the array
- print_report() formats the result
If a number in the report is wrong, the stage that produced it is the only place you need to look.
General pattern
#define CAPACITY 8
struct Record { char name[16]; int value; };
int parse_record(const char *line, struct Record *out); /* 1 = valid */
double summarise(const struct Record list[], int count); /* no I/O */
void print_records(const struct Record list[], int count); /* only I/O */
/* main: for each line, if count < CAPACITY and parse_record(...)
succeeds, count++; then summarise and print */Declare the data shape, then give each stage one function. Input functions fill a struct through a pointer and report success; logic functions take a const array plus a count; only the output function prints.
The score report, layer by layer
The program feeds itself six scripted lines, exactly the kind of text a user might type, so every run gives the same output. Two lines are bad on purpose: "Daw abc" has no number and "Ei 105" is out of range. Watch how they are rejected at the door with a message naming the line, while the four good students flow through to the report.
The task needs a row per student with a result, a count of passes and the average. Note which function owns each part, because the challenge reuses these layers in a different program.
#include <stdio.h>
#define MAX_STUDENTS 8
#define PASS_MARK 60
struct Student {
char name[16];
int score;
};
/* Input layer: one "name score" line -> Student. Returns 1 if valid. */
int parse_line(const char *line, struct Student *out) {
char extra;
if (sscanf(line, "%15s %d %c", out->name, &out->score, &extra) != 2) {
return 0;
}
return out->score >= 0 && out->score <= 100;
}
/* Logic layer: numbers in, numbers out. No printf, no input. */
double average(const struct Student list[], int count) {
if (count == 0) {
return 0.0;
}
int total = 0;
for (int i = 0; i < count; i++) {
total += list[i].score;
}
return total / (double)count;
}
int count_passed(const struct Student list[], int count) {
int passed = 0;
for (int i = 0; i < count; i++) {
if (list[i].score >= PASS_MARK) {
passed++;
}
}
return passed;
}
/* Output layer: the only place that formats the report. */
void print_report(const struct Student list[], int count) {
printf("%-6s %5s %s\n", "Name", "Score", "Result");
for (int i = 0; i < count; i++) {
const char *result = list[i].score >= PASS_MARK ? "Passed" : "Try again";
printf("%-6s %5d %s\n", list[i].name, list[i].score, result);
}
printf("Passed: %d of %d\n", count_passed(list, count), count);
printf("Average score: %.2f\n", average(list, count));
}
int main(void) {
/* Scripted input: the lines a user would type, so the run is repeatable. */
const char *input[] = {"Aye 75", "Bo 82", "Chit 68", "Daw abc", "Ei 105", "Hla 45"};
int lines = (int)(sizeof input / sizeof input[0]);
struct Student list[MAX_STUDENTS];
int count = 0;
for (int i = 0; i < lines; i++) {
if (count == MAX_STUDENTS) {
printf("List is full, ignoring the rest\n");
break;
}
if (parse_line(input[i], &list[count])) {
count++;
} else {
printf("Skipped line %d: \"%s\"\n", i + 1, input[i]);
}
}
print_report(list, count);
return 0;
}Code breakdown
- Reject trailing junk
if (sscanf(line, "%15s %d %c", out->name, &out->score, &extra) != 2) {sscanf returns how many items it filled. A valid line fills the name and the score and then finds nothing for %c, so the result is exactly 2. "Aye 7x" fills 3 because x lands in extra, and "Daw abc" fills only 1. The 15 in %15s stops a long name from overflowing the 16-byte array.
- Range check as the return value
return out->score >= 0 && out->score <= 100;A comparison in C evaluates to 1 or 0, so the function can return the range check directly. That is why "Ei 105" parses as text but is still rejected.
- Capacity before writing
if (count == MAX_STUDENTS) {The check happens before parse_line writes into list[count]. With 8 slots, list[8] would be past the end, and C would not stop you.
- Floating-point division
return total / (double)count;Casting one operand makes the division happen in double: 270 / 4.0 gives 67.5. The count == 0 guard above it avoids dividing by zero for an empty list.
- Counting the array length
int lines = (int)(sizeof input / sizeof input[0]);sizeof the whole array divided by sizeof one element gives 6. This only works where input is a real array; inside a function that received it as a pointer, sizeof would give the pointer's size instead.
Skipped line 4: "Daw abc"
Skipped line 5: "Ei 105"
Name Score Result
Aye 75 Passed
Bo 82 Passed
Chit 68 Passed
Hla 45 Try again
Passed: 3 of 4
Average score: 67.50Swapping the scripted lines for real input
The scripted array keeps this lesson repeatable, but in a real program the lines come from the keyboard or a file. The good news is that parse_line() does not change at all. Only main()'s loop changes, reading each line into a buffer with fgets: char line[64]; while (count < MAX_STUDENTS && fgets(line, sizeof line, stdin) != NULL) { ... }
fgets stops at the newline or when the buffer is full, and returns NULL at the end of input, so the loop ends cleanly when the user presses Ctrl+D (Ctrl+Z then Enter on Windows). The newline that fgets keeps is skipped by the space before %c, so parse_line accepts the line as it is. Because the whole line is read first and parsed second, a bad line can never get stuck in the input the way it does with scanf.
In real projects
In real projects
The same split shows up in real C tools far bigger than this one. A command-line utility such as a log analyser has a parser that turns each line into a struct, analysis functions that never print, and a formatter that can output plain text or CSV. Embedded firmware handles sensor readings the same way: one function validates the raw value from the hardware, another averages it, and a third sends it to a display.
The payoff is testing. Because average() and parse_line() take plain arguments and return plain results, a test file can call them with dozens of tricky inputs, such as an empty list, a score of exactly 60 or a name that is too long, without anyone typing at a keyboard. When a team adds a feature, it usually lands in exactly one layer: a new column touches only the printer, a new rule only the logic.
Common mistakes
Common mistakes
Ignoring the return value of scanf or sscanf
The variables you pass are only filled when the return value says so. Skip the check and a failed read leaves an uninitialised variable that you then add, compare or print. Always compare the result with the number of items you asked for.
Writing before checking the capacity
Calling parse_line(input[i], &list[count]) when count already equals MAX_STUDENTS writes one element past the end of the array. The program may keep running and print a perfect-looking report while it silently corrupts another variable. Check the count first, then write.
Casting after the division
(double)(total / count) looks right but converts an int that has already been truncated: 270 / 4 becomes 67, then 67.0. Put the cast on one operand, as in total / (double)count.
Printing inside logic functions
If average() prints its own result, you cannot reuse it for a CSV export or a test without that extra line appearing. Return the value and let the output layer decide what to show.
Mini challenge
Build a contact book with a growing array
Use the same layers for a different program: a contact book that reads "name,phone" lines, stores them in a heap array that grows when it is full, refuses duplicate names, looks contacts up by name, and frees everything through one cleanup function.
- parse_contact() accepts "name,phone" only when the phone is 3 to 15 digits
- book_add() returns 1 when added, 0 for a duplicate name, -1 if realloc fails
- The array starts empty and doubles its capacity (2, 4, 8...) when full
- book_find() returns a pointer to the contact, or NULL when the name is missing
- book_free() releases the array once, and main() calls it on the way out
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Contact {
char name[24];
char phone[16];
};
struct ContactBook {
struct Contact *items; /* heap array, NULL while the book is empty */
size_t count;
size_t capacity;
};
int parse_contact(const char *line, struct Contact *out) {
// TODO: split "name,phone" (hint: %23[^,]), reject anything extra,
// then make sure the phone is 3-15 digits. Return 1 if valid.
}
const struct Contact *book_find(const struct ContactBook *book, const char *name) {
// TODO: return a pointer to the matching contact, or NULL
}
int book_add(struct ContactBook *book, const struct Contact *c) {
// TODO: return 0 for a duplicate name
// TODO: when count == capacity, grow with realloc into a temporary pointer
// TODO: copy *c into the next slot and return 1
}
void book_free(struct ContactBook *book) {
// TODO: free the array and reset all three fields
}
int main(void) {
const char *input[] = {"Aye,0912345678", "Bo,09777", "Aye,0999999999",
"Chit 0911", "Daw,09-123", "Ei,0944444444"};
// TODO: parse and add each line, reporting bad lines and duplicates
// TODO: print count and capacity, look up "Bo" and "Zaw", free the book
}Expected: Aye, Bo and Ei are added; the second Aye is reported as a duplicate; "Chit 0911" and "Daw,09-123" are bad lines. The book ends with 3 contacts and capacity 4, Bo's number is found and Zaw is not found.
Show hint
For the split, "%23[^,],%15s %c" reads up to 23 characters that are not commas, a comma, then the phone; a result of 2 means nothing extra followed. When growing, store realloc's result in a new pointer and assign it to book->items only after checking it is not NULL, so a failure cannot lose the old array.
Show solution
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Contact {
char name[24];
char phone[16];
};
struct ContactBook {
struct Contact *items;
size_t count;
size_t capacity;
};
/* "name,phone" -> Contact. Phone must be 3-15 digits. Returns 1 if valid. */
int parse_contact(const char *line, struct Contact *out) {
char extra;
if (sscanf(line, "%23[^,],%15s %c", out->name, out->phone, &extra) != 2) {
return 0;
}
size_t len = strlen(out->phone);
if (len < 3) {
return 0;
}
for (size_t i = 0; i < len; i++) {
if (!isdigit((unsigned char)out->phone[i])) {
return 0;
}
}
return 1;
}
const struct Contact *book_find(const struct ContactBook *book, const char *name) {
for (size_t i = 0; i < book->count; i++) {
if (strcmp(book->items[i].name, name) == 0) {
return &book->items[i];
}
}
return NULL;
}
/* 1 = added, 0 = duplicate name, -1 = out of memory (book unchanged). */
int book_add(struct ContactBook *book, const struct Contact *c) {
if (book_find(book, c->name) != NULL) {
return 0;
}
if (book->count == book->capacity) {
size_t new_cap = book->capacity == 0 ? 2 : book->capacity * 2;
struct Contact *bigger = realloc(book->items, new_cap * sizeof *bigger);
if (bigger == NULL) {
return -1;
}
book->items = bigger;
book->capacity = new_cap;
}
book->items[book->count] = *c;
book->count++;
return 1;
}
void book_free(struct ContactBook *book) {
free(book->items);
book->items = NULL;
book->count = 0;
book->capacity = 0;
}
int main(void) {
const char *input[] = {"Aye,0912345678", "Bo,09777", "Aye,0999999999",
"Chit 0911", "Daw,09-123", "Ei,0944444444"};
size_t lines = sizeof input / sizeof input[0];
struct ContactBook book = {NULL, 0, 0};
for (size_t i = 0; i < lines; i++) {
struct Contact c;
if (!parse_contact(input[i], &c)) {
printf("Bad line: \"%s\"\n", input[i]);
continue;
}
int result = book_add(&book, &c);
if (result == 1) {
printf("Added %s\n", c.name);
} else if (result == 0) {
printf("Duplicate: %s\n", c.name);
} else {
printf("Out of memory\n");
break;
}
}
printf("%zu contacts, capacity %zu\n", book.count, book.capacity);
const char *wanted[] = {"Bo", "Zaw"};
for (size_t i = 0; i < 2; i++) {
const struct Contact *found = book_find(&book, wanted[i]);
printf("%s -> %s\n", wanted[i], found ? found->phone : "not found");
}
book_free(&book);
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Split a program along the data path: input, storage, logic, output
- Trust sscanf's return value, not the variables, and use %c to catch trailing junk
- Check an array's capacity before writing the next element
- Cast one operand (total / (double)count) to keep the fraction
- Logic functions that never print are easy to test and reuse
AddressSanitizer — LLVM/Clang