Practice Exercises
Try your hand at these compound programming challenges. You can write and run your code directly in the interactive R editor boxes below, and check your work against the hidden solutions once completed.
Exercise 1: Running Statistics Calculator
Write an R script that continuously prompts the user to enter a number.
- The program should maintain a running history of all numbers entered.
- After each input, it should display:
- The current running average (mean) of all entered numbers.
- The current maximum value entered.
- The current minimum value entered.
- The user can type
"quit"(case-insensitive) to stop the program. - The program must handle invalid inputs (e.g., if the user types letters instead of numbers) gracefully without throwing errors or crashing.
- Print all statistical values rounded to 2 decimal places.
Hint: Use a repeat or while loop, readline() for input, as.numeric() for conversion, and a vector to store the history of numbers.
# Write your R script below and click Run Code
Click to view Answer
numbers <- c()
repeat {
user_input <- readline(prompt = "Enter a number (or type 'quit' to exit): ")
# Check for exit condition
if (tolower(user_input) == "quit") {
print("Exiting calculator. Goodbye!")
break
}
# Try to convert input to numeric
num <- as.numeric(user_input)
# Check if conversion failed (is.na returns TRUE for invalid numbers)
if (is.na(num)) {
print("Invalid Input! Please enter a valid number.")
next # Skip to next loop iteration
}
# Add valid number to history
numbers <- c(numbers, num)
# Compute running stats
avg_val <- round(mean(numbers), 2)
max_val <- round(max(numbers), 2)
min_val <- round(min(numbers), 2)
# Print stats
print(paste("Numbers Entered:", length(numbers)))
print(paste("Running Average:", avg_val))
print(paste("Maximum Value :", max_val))
print(paste("Minimum Value :", min_val))
print("---------------------------------")
}
Exercise 2: Number Guessing Game
Write a guessing game in R.
- When the program starts, it should generate a random integer in memory between
20and50(inclusive). Hint: Usesample(20:50, 1)to generate a single random integer. - The program should repeatedly ask the user to guess the number.
- Handle exceptions and invalid input gracefully (e.g. typing characters).
- Provide the following hints to the user to guide them:
- If the guess is more than 10 below the target: print
"Your guess is too low. Try again." - If the guess is 10 or less below the target: print
"Your guess is low. Try again." - If the guess is more than 10 above the target: print
"Your guess is too high. Try again." - If the guess is 10 or less above the target: print
"Your guess is high. Try again."
- If the guess is more than 10 below the target: print
- Once the user guesses the correct number, print:
"Congratulations, you guessed it right in X attempts!"(where X is the number of attempts). - If the user wants to quit, they can type
"quit"to terminate the game.
# Write your R script below and click Run Code
Click to view Answer
# Generate random number
target <- sample(20:50, 1)
attempts <- 0
print("Welcome to the Guessing Game!")
print("I've picked a number between 20 and 50. Can you guess it?")
print("Type 'quit' to end the game.")
repeat {
user_input <- readline(prompt = "Enter your guess: ")
# Check for exit condition
if (tolower(user_input) == "quit") {
print(paste("Game ended. The correct number was:", target))
break
}
# Try to convert input to numeric integer
guess <- as.integer(user_input)
attempts <- attempts + 1
# Validate input
if (is.na(guess)) {
print("Invalid guess! Please enter a valid integer.")
next
}
# Game matching logic
if (guess == target) {
print(paste("Congratulations, you guessed it right in", attempts, "attempts!"))
break
} else if (guess < target) {
difference <- target - guess
if (difference > 10) {
print("Your guess is too low. Try again.")
} else {
print("Your guess is low. Try again.")
}
} else {
difference <- guess - target
if (difference > 10) {
print("Your guess is too high. Try again.")
} else {
print("Your guess is high. Try again.")
}
}
}