Menu
Coddy logo textTech

Recap - Reversed Vector

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

challenge icon

Challenge

Easy

You will receive a single line of input containing comma-separated numbers (e.g., 10,20,30,40,50).

Perform the following operations:

  1. Create a vector from the comma-separated input
  2. Reverse the vector so the last element becomes first
  3. Print the reversed vector
  4. Print the sum of the first and last elements of the reversed vector

For example, if the input is:

5,15,25,35,45

The output should be:

[1] 45 35 25 15  5
[1] 50

Explanation: The original vector c(5, 15, 25, 35, 45) is reversed to c(45, 35, 25, 15, 5). The sum of the first element (45) and last element (5) of the reversed vector is 50.

Try it yourself

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

# Parse the comma-separated numbers into a vector
numbers <- as.numeric(strsplit(input, ",")[[1]])

# TODO: Write your code below
# 1. Reverse the vector
# 2. Print the reversed vector
# 3. Calculate and print the sum of first and last elements of the reversed vector

All lessons in Fundamentals