C/C++ Arena

Step 4 of 7

Arrays of structs

An array of structs is like a table: each element is one row, and the members are the columns. This is how a lot of real data is organized: a list of players, products, students or events.

#include <stdio.h>

struct City {
    char name[20];
    int population;
};

int main(void) {
    struct City cities[3];
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%19s %d", cities[i].name, &cities[i].population);
    }
    int smallest = 0;
    for (int i = 1; i < n; i++) {
        if (cities[i].population < cities[smallest].population) {
            smallest = i;
        }
    }
    printf("smallest: %s\n", cities[smallest].name);
    return 0;
}
3
Lyon 516000
Nice 342000
Lille 236000
smallest: Lille

Reading the syntax

cities[i].name means: element i of the array, then its name member. When reading input, name is a char array so it needs no &, while population is an int so it needs &cities[i].population.

Track the index, not the value

The loop remembers which element is best (smallest, an index), not just the best number. That way you can print any member of the winning row afterwards. Start with element 0 as the best and compare the rest against it.

Ties

With < (strictly less), a later element only replaces the current best if it's strictly better, so the first of several equal values wins. With <=, the last one would win. Choosing the right comparison is how you control tie-breaking.

Your turn: the input is n followed by n lines of name kills. Print the name of the player with the most kills (the first one wins ties).

3
ropz 18
broky 25
rain 25

prints MVP: broky.

Previous: Pointers to structs and -> Next: enum