Menu
Coddy logo textTech

Recap - Age Calculator

Part of the Fundamentals section of Coddy's R journey — lesson 31 of 78.

challenge icon

Challenge

Easy

Build a simple age calculator that reads a birth year and the current year, then calculates and displays the person's age.

You will receive two inputs:

  1. A birth year
  2. The current year

Read both inputs using readline(), convert them to numeric values using as.numeric(), and calculate the age by subtracting the birth year from the current year.

Display the output in the following format:

You are [age] years old

Use cat() for the output and include a newline character \n at the end.

For example, if the inputs are 1995 and 2024, the output should be:

You are 29 years old

Try it yourself

# Read input
con <- file("stdin", "r")
birth_year <- suppressWarnings(readLines(con, n = 1))
current_year <- suppressWarnings(readLines(con, n = 1))

# TODO: Convert inputs to numeric and calculate the age


# Output the result in the format: "You are [age] years old"
cat("You are", age, "years old\n")

All lessons in Fundamentals