Store a student's name and two scores, then calculate the total and average.
I. Objectives
Combine input and output, arithmetic, an array, a string, and a structure in one small program.
Use valid array indexes and floating-point division when calculating an average.
Before the Lab
Weeks 1–3: create and run a program; use input, output, variables, arithmetic, arrays, std::string, std::getline, and structures. Use the dot operator and valid array indexes.
II. Environment
A computer with Windows, macOS, or Linux.
Use OnlineGDB in C++ mode, or the C++ environment demonstrated in class.
Save your program as lab01.cpp. Use one source file for this lab.
Complete the TODOs in the starter code, then compare your result with the expected output. The starter is intentionally unfinished.
Task 1 — Read the record and complete the input
StudentRecord groups a name and two integer scores. Find student.name, student.scores[0], and student.scores[1]. The supplied std::getline reads a full name, including spaces. At TODO 1, use std::cin to read the two scores into the array. Enter the name on the first line and the scores on the next line.
Task 2 — Calculate the total and average
At TODO 2, replace 0 with the sum of the two array elements. At TODO 3, replace 0.0 with total / 2.0. Keep the supplied output statements. The starter prints zero for the total and average until these expressions are completed.
Task 3 — Test the student record
Use integer scores from 0 to 100. Test Ada Lovelace with 80 and 85: total 165, average 82.5. Then test Alex with 0 and 100: total 100, average 50; and Sam with 100 and 100: total 200, average 100. Explain why the only valid indexes are 0 and 1. Loops, branching statements, pointers, and user-defined functions are not required.
#include <iostream>
#include <string>
struct StudentRecord {
std::string name;
int scores[2]{};
};
int main() {
StudentRecord student{};
std::getline(std::cin, student.name);
// TODO 1: Read the two scores into the array.
int total = 0; // TODO 2: Add the two scores.
double average = 0.0; // TODO 3: Divide the total by 2.0.
std::cout << "Name: " << student.name << '\n';
std::cout << "Total: " << total << '\n';
std::cout << "Average: " << average << '\n';
return 0;
}
Expected Output
Expected output after completing all TODOs, with Ada Lovelace on the first input line and 80 85 on the second.
Name: Ada Lovelace
Total: 165
Average: 82.5
IV. Lab Report Submission
Submit one lab report for this lab, in English or Chinese. Include the following content in the report.