Skip to content

Checkpoint: Group a Sorted Report

The Course
•
40 min study

After sorting, all records with the same topic sit next to each other. That turns grouping into one pass: start a group at the first record, keep going while the topic stays the same, print the group's count and total, and start the next group where the topic changes. No lookup table, no second allocation, and each record is visited once. This is the loop at the heart of the project's analyzer_report, and it is easy to get subtly wrong at the edges: the first record, the last record and the empty array.

Predict and run

Read the program before pressing Run. Write down its output and explain why the inner loop tests i < 5 first.

Predict before running C
#include <stdio.h>

int main(void) {
    int sorted[5] = {1, 1, 2, 3, 3};
    size_t i = 0;
    while (i < 5) {
        size_t start = i;
        while (i < 5 && sorted[i] == sorted[start]) { ++i; }
        printf("%d: %zu\n", sorted[start], i - start);
    }
    return 0;
}
Check your prediction
Text
1: 2
2: 1
3: 2

start marks the first element of a group, and the inner loop moves i to the first element of the next group, so i - start is the group's size. When the last group ends, i is 5. The && operator evaluates left to right and skips the right side when the left side is false, so sorted[5] is never read. Swap the two conditions and the last iteration reads one element past the array: undefined behavior that may well print the right answer anyway, which is what makes it dangerous.

Bug hunt: a loop that never ends

Someone "tidied" the inner condition to i + 1 < 5. A grouping loop with that kind of slip does not print a wrong number and stop; it runs forever, and the browser editor shows output piling up until you press Stop. To keep this run short, the program below counts outer passes and gives up after 6, which is a useful trick whenever you suspect a loop is not making progress. Run it, then answer: on which pass does i stop moving, and why?

Fix: the loop that stops advancing C
#include <stdio.h>

int main(void) {
    int sorted[5] = {1, 1, 2, 3, 3};
    size_t i = 0;
    int passes = 0;
    while (i < 5) {
        if (++passes > 6) {
            printf("gave up: i is stuck at %zu\n", i);
            return 1;
        }
        size_t start = i;
        while (i + 1 < 5 && sorted[i] == sorted[start]) { ++i; }
        printf("%d: %zu\n", sorted[start], i - start);
    }
    return 0;
}
Shell
1: 2
2: 1
3: 1
3: 0
3: 0
3: 0
gave up: i is stuck at 4
Check your fix

At i == 4, i + 1 < 5 is false before the topic is even compared, so the inner loop runs zero times and i stays 4. The outer loop sees i < 5 still true and starts the same empty group again, for ever. (The third line already shows the damage: the last 3 was never counted.) Every pass of the outer loop must move i, and the inner loop guarantees that only if it can always take its first step: the record at start matches itself. Restore the bound to i < 5:

C
#include <stdio.h>

int main(void) {
    int sorted[5] = {1, 1, 2, 3, 3};
    size_t i = 0;
    int passes = 0;
    while (i < 5) {
        if (++passes > 6) {
            printf("gave up: i is stuck at %zu\n", i);
            return 1;
        }
        size_t start = i;
        while (i < 5 && sorted[i] == sorted[start]) { ++i; }
        printf("%d: %zu\n", sorted[start], i - start);
    }
    return 0;
}
Text
1: 2
2: 1
3: 2

The rule to carry into your own loop: the inner loop's bound must allow the element at start itself, so each outer pass makes progress.

What you will use

  • A sorted array of records, ordered by topic and then minutes, as the sorting lesson produced.
  • Two indexes: start for the group's first record, i for the record being examined.
  • strcmp to decide whether record i belongs to the group started at start.
  • A long accumulator per group, since minutes for 1024 records can exceed the guaranteed range of int.

Plan before you type

Goals, not statements.

  1. Decide what the empty array prints, and make sure no group code runs for it.
  2. Make each outer pass handle exactly one group and leave i at the first record of the next one.
  3. Make the inner loop's bound safe at the last record (no read past the end) and always able to take its first step (progress).
  4. Check that the session counts add up to the array's count.
Prove it can fail

With the expected lines showing, try three breakages one at a time. Reverse the inner loop's conditions so the strcmp comes first: the output probably does not change, which shows why a sanitizer build (-fsanitize=address) is worth running locally, since it reports the one-past-the-end read. Next, swap the bound for the bug hunt's i + 1 < count, and add the bug hunt's pass counter first so the run cannot hang: reading reports 1 session, then the same empty group repeats. Finally, remove the empty check: the No records line disappears and nothing is printed for empty input. Restore everything.

Why the project sorts a copy, and what can still fail

The report must not reorder the stored records, so analyzer_report copies them into a temporary block before sorting. That allocation can fail. The contract says a failed report prints nothing and returns ANALYZER_NOMEM, so the caller never sees half a report. Printing can also fail, for example when output goes to a full disk. That failure is different: some lines may already be written. fprintf reports errors through the stream, so main checks ferror(stdout) after printing and exits with a failure status.

Mistakes worth checking for

  • The first record forms its own group. The inner loop compares i with i - 1 instead of with start, or i is increased before the comparison.
  • An infinite loop on the first group. The inner loop compares sorted[start] with itself and never moves i, or the outer loop resets i to start.
  • The last group is missing. Printing happens only when the topic changes, so the group still open at the end of the array is never printed. Print after each inner loop instead.
  • Totals keep growing across groups. The group total is declared outside the outer loop and never reset.
  • Groups are split, such as two reading lines. The input was not sorted by topic, so equal topics were not adjacent. Grouping depends on sorting.

Practice

Exercise

Your turn

Write void print_groups(const Record sorted[], size_t count) following the plan. The starter calls it on a sorted array and then on an empty one. Expected output: art: 1 sessions, 30 minutes, coding: 2 sessions, 70 minutes, reading: 2 sessions, 35 minutes, then No records.

Your workspace C
#include <stdio.h>
#include <string.h>

typedef struct { char topic[24]; int minutes; } Record;

/* Write print_groups here. */

int main(void) {
    const Record sorted[5] = {
        {"art", 30}, {"coding", 30}, {"coding", 40}, {"reading", 10}, {"reading", 25},
    };
    print_groups(sorted, 5);
    print_groups(sorted, 0);
    return 0;
}
Hint 1: the idea

Every record belongs to exactly one group, and every group starts where the previous one ended. If the session counts add up to the array's count, no record was skipped or counted twice.

Hint 2: a first step

Ignore minutes at first. Make print_groups print only each group's topic and size, such as coding: 2, and check the three sizes add up to 5. Topics are strings, so compare them with strcmp, not ==. Add the minutes once the sizes are right.

Show one solution
Run the solution C
#include <stdio.h>
#include <string.h>

typedef struct { char topic[24]; int minutes; } Record;

void print_groups(const Record sorted[], size_t count) {
    if (count == 0) {
        printf("No records\n");
        return;
    }
    size_t i = 0;
    while (i < count) {
        size_t start = i;
        long minutes = 0;
        while (i < count && strcmp(sorted[i].topic, sorted[start].topic) == 0) {
            minutes += sorted[i].minutes;
            ++i;
        }
        printf("%s: %zu sessions, %ld minutes\n", sorted[start].topic, i - start, minutes);
    }
}

int main(void) {
    const Record sorted[5] = {
        {"art", 30}, {"coding", 30}, {"coding", 40}, {"reading", 10}, {"reading", 25},
    };
    print_groups(sorted, 5);
    print_groups(sorted, 0);
    return 0;
}
Text
art: 1 sessions, 30 minutes
coding: 2 sessions, 70 minutes
reading: 2 sessions, 35 minutes
No records

The inner loop always runs at least once, because the record at start matches itself, so i always moves forward and the outer loop must end. The sessions 1 + 2 + 2 add up to 5, the sanity check from Hint 1. The output says "1 sessions" because the project's format keeps one fixed word; making it plural-aware would change only the printf, not the grouping. Tomorrow you separate the library from the program that uses it and make allocation failure testable.

Was this article helpful?

Your response is saved on this device.