Arrays of Structures
Imagine a list of mountains, each with a name and a height. One mountain is one structure. To keep more of them, you already know what to use: an array. A structure is a type like any other, so you can make an array of structures:
#include <stdio.h>
typedef struct {
char name[20];
int height;
} Mountain;
int main(void) {
Mountain mountains[3] = {
{"Everest", 8849},
{"K2", 8611},
{"Lhotse", 8516}
};
for (int i = 0; i < 3; i++) {
printf("%-8s %5d m\n", mountains[i].name, mountains[i].height);
}
return 0;
}This prints:
Everest 8849 m
K2 8611 m
Lhotse 8516 mEach element of the array is written as a structure of its own in curly braces, and the elements are separated by commas, as in any array. mountains[0] is the whole first mountain, Everest. mountains[i].name is read from left to right: first take element i of the array, then its member name.
A typical mistake is to swap the order and write mountains.name[i]. That means "the member name of the array mountains", but an array has no members, only elements:
main.c:16:41: error: member reference base type 'Mountain[3]' is not a structure or union
16 | printf("%-8s %5d m\n", mountains.name[i], mountains[i].height);
| ~~~~~~~~~^~~~~The message says that what stands before the dot, of type Mountain[3] (an array of three mountains), is not a structure. (A union is something similar to a structure that this course doesn't use.)
As in the lesson on strings, the printf in the loop sets the width of each column, so that the columns line up. %-8s prints the text in a column 8 characters wide, aligned to the left (that's what the - does), and %5d prints the number in a column 5 characters wide, aligned to the right. With decimal numbers, %6.2f means 2 decimal places and a width of 6 characters in total.
Instead of writing the count 3 in the loop, you can let the program work it out, as with any array: const int COUNT = sizeof(mountains) / sizeof(mountains[0]); The size of the whole array divided by the size of one element is the number of elements, whatever the elements are.
Instructions
The program prints only the first product in the cart. Replace the printf with a for loop that prints every product in the same way. The program prints:
Bread 32.50 x 2
Milk 24.90 x 3
Apples 8.50 x 6Below the loop, print what the whole cart costs. For every product, multiply its price by its count, and add up the results; you can do it in the same loop or in a new one. Print the result with 2 decimal places: Total: 190.70.
Start programming for free
4/9