BETA Try the new lesson view
Code

An array of cities

Now five cities in an array: sort them, find one and work out a density.

Extend cities.c:

  • #include <string.h> and #define CITY_COUNT 5;
  • double density(const City *c) – population / area. The precondition c->area > 0: dividing by 0 would make no sense;
  • int find_city(const City t[], int n, const char *name) – a linear search with strcmp, an index or -1;
  • void sort_by_population(City t[], int n) – selection sort, descending, swapping whole structures;
  • at the end of main – the array cities[CITY_COUNT], the sort, a numbered list, the search for Alytus with its density, and for Utena, which isn't on the list.

The earlier part of main stays as it was.

Run it

p10_cities and ▶:

Kaunas: 300000 people, 157.0 km2
Vilnius: 600000 people, 401.0 km2
sizeof(City): 32
kaunas: 300000, copy: 0
After grow_copy: 300000
After grow:      301000

By population:
1. Vilnius: 600000 people, 401.0 km2
2. Kaunas: 300000 people, 157.0 km2
3. Klaipeda: 150000 people, 98.0 km2
4. Panevezys: 85000 people, 50.0 km2
5. Alytus: 50000 people, 40.0 km2
Alytus is in place 5, density 1250 people/km2
Utena is not on the list.

The areas were sorted along with the populations – because whole structures were swapped. find_city searches the already sorted array, so it returns the place after sorting.

By name

Change the comparison in sort_by_population to strcmp(t[j].name, t[max].name) < 0 and run it. The cities line up A, K, K, P, V: strcmp compares the names byte by byte, and for Latin letters that is alphabetical order. Put the comparison back (Ctrl+Z).

Commit: Sort and search cities.