MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Setup
  • 1A: Fundamental Building Blocks
  • 1B: Compound Statements
  • 2: Ordered Collection
  • 3: Key-Value Map and Structures
  • 4: More Data types
  • 5: Iteration Constructs
  • 6: Other constructs
  • 7. Regex
  • 8. Date and Time
  • Revision
  • Practice Exercise

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.

  1. The program should maintain a running history of all numbers entered.
  2. 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.
  3. The user can type "quit" (case-insensitive) to stop the program.
  4. The program must handle invalid inputs (e.g., if the user types letters instead of numbers) gracefully without throwing errors or crashing.
  5. 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.

  1. When the program starts, it should generate a random integer in memory between 20 and 50 (inclusive). Hint: Use sample(20:50, 1) to generate a single random integer.
  2. The program should repeatedly ask the user to guess the number.
  3. Handle exceptions and invalid input gracefully (e.g. typing characters).
  4. 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."
  5. Once the user guesses the correct number, print: "Congratulations, you guessed it right in X attempts!" (where X is the number of attempts).
  6. 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.")
    }
  }
}
Privacy Policy | Terms & Conditions