CodeBlanks Logo Icon CodeBlanks

Summary - Arrays

Use single and multidimensional arrays to write a grade table.

Summary - Arrays

In this section you learned array declaration, access, sizeof, multidimensional arrays and iterating with loops. Now we'll combine them in a grade table app.

The app holds a student's three exam grades in an array; computes the average and assigns a letter grade. It uses both a single-dimensional array and a for loop.

Practice Average of three grades

Write a C program. Declare int scores[3] = {80, 90, 70};. Initialize int sum = 0;. With for (int i = 0; i < 3; i++) do sum += scores[i];. Print the average with printf("Average: %d\n", sum / 3);. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare scores, sum with for, print the average
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int scores[3] = {80, 90, 70};
    int sum = 0;
    for (int i = 0; i < 3; i++) {
        sum += scores[i];
    }
    printf("Average: %d\n", sum / 3);
    return 0;
}

Expected output

Average: 80

Practice Multidimensional grade table

Write a C program. Declare int grades[2][3] = {{80, 90, 70}, {85, 95, 75}}; (two students, three exams). Print the first student's first grade and the second student's last grade with printf("%d %d\n", grades[0][0], grades[1][2]);. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare the grades matrix, print two elements
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int grades[2][3] = {{80, 90, 70}, {85, 95, 75}};
    printf("%d %d\n", grades[0][0], grades[1][2]);
    return 0;
}

Expected output

80 75

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is the average of three grades computed?

main.c
int scores[3] = {80, 90, 70};
int sum = 0;
for (int i = 0; i < 3; i++) sum += scores[i];
  • scores[0]
  • sum * 3
  • sum / 3 Correct answer
  • 3 / sum

Explanation: The sum is divided by the count.

2 Complete the array declaration

Question
int ____[3] = {80, 90, 70};
Answer
int scores[3] = {80, 90, 70};

Explanation: scores is the array name.

3 Match the array concepts

Term Meaning
int scores[3] Array declaration
scores[0] First element
sizeof Byte measure
sum += scores[i] Accumulation

All lessons in Beginner