Menu
Coddy logo textTech

Adding Students

Part of the Logic & Flow section of Coddy's R journey. Lesson 22 of 64.

In this project you build a gradebook that reads commands, one per line, and replies to each one. Over five steps it learns to add students, record grades, report averages and find the top student. Every step extends the same gradebook(commands) function.

ADD ada
GRADE ada 90
AVG ada
REPORT
TOP

The grades live in a named list: each student's name maps to a numeric vector of that student's grades. A list fits because every student holds several values.

grades <- list()
grades[["ada"]] <- numeric(0)
grades[["ada"]] <- c(grades[["ada"]], 90)
print(length(grades[["ada"]]))
print(names(grades))

Output:

[1] 1
[1] "ada"

numeric(0) is an empty numeric vector. Assigning c() would not work here: it is NULL, and assigning NULL removes a list entry.

Each command is split at spaces, so parts[1] is the command and parts[2] the name. An if / else if chain picks what to do:

for (cmd in commands) {
  parts <- strsplit(cmd, " ")[[1]]
  name <- parts[2]
  if (parts[1] == "ADD") {
    # handle ADD
  }
}

The replies are collected with replies <- c(replies, ...) and returned at the end.

challenge icon

Challenge

Easy

Complete gradebook(commands) for the first command:

  • ADD <name>: if the student is new, store them with no grades and reply added <name>. If the name is already stored, reply <name> already exists.

The supplied code passes every input line to gradebook() as one command and prints each returned reply on its own line. A name is one lower-case word, and the input holds only the commands described so far.

Try it yourself

gradebook <- function(commands) {
  grades <- list()
  replies <- c()
  for (cmd in commands) {
    parts <- strsplit(cmd, " ")[[1]]
    name <- parts[2]
    # Write your code here
  }
  replies
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(gradebook(input), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler