Array of Structures in C

Level 5208 keystrokes

Defines a Student struct, initializes an array of three students with nested braces and loops over it, reading each member with students[i].name and students[i].score. It prints Tom: 85, Amy: 92 and Bob: 78.

C code

// One record per student: a name and a score
1struct Student {
// Name of up to 9 characters plus '\0'
2 char name[10];
// Test score
3 int score;
4};
5
// An array of 3 structs; each inner pair of braces fills one element
6struct Student students[3] = {
// students[0]: name "Tom", score 85
7 {"Tom", 85},
// students[1]: "Amy", 92
8 {"Amy", 92},
// students[2]: "Bob", 78
9 {"Bob", 78}
10};
11
// Visits the three students in order
12for (int i = 0; i < 3; i++) {
// Indexes the array, then uses a dot for the member: Tom: 85, Amy: 92, Bob: 78
13 printf("%s: %d\n", students[i].name, students[i].score);
14}

Output

Tom: 85
Amy: 92
Bob: 78
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • "× 8
  • ,× 7
  • ;× 7
  • {× 6
  • }× 6
  • [× 4
  • ]× 4
  • .× 2
  • (× 2
  • )× 2

More C examples at level 5

← C typing practice