Menu
Coddy logo textTech

Recap - Sigma Function

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

challenge icon

Challenge

Easy

Create a function called sigma that takes one argument n and returns the sum of all integers from 1 to n.

Read a number from input, convert it to a numeric value, and call your sigma function with this value. Print the returned result.

For example, if the input is 5, your function should calculate 1 + 2 + 3 + 4 + 5 = 15, and the output should be:

[1] 15

If the input is 10, your function should calculate the sum from 1 to 10, and the output should be:

[1] 55

If the input is 1, the output should be:

[1] 1

Try it yourself

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

# TODO: Create a function called 'sigma' that takes one argument 'n'
# and returns the sum of all integers from 1 to n


# Call the function and print the result
print(sigma(n))

All lessons in Fundamentals