Recap - Age Calculator
Part of the Fundamentals section of Coddy's R journey — lesson 31 of 78.
Challenge
EasyBuild 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:
- A birth year
- 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 oldUse 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 oldTry 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
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values