Here we are explaining how to write an R program to find the sum of natural numbers. We can use the readline() function to take input from the user (terminal). Here the prompt argument can choose to display an appropriate message for the user.
From mathematics, we know that sum of natural numbers is given by
n*(n+1)/2
We are using readline() function for taking the user’s input. Given below are the steps which are used in the R program to find the sum of natural numbers up to the given limit. In this R program, we accept the user’s values into n by providing an appropriate message to the user using ‘prompt’. We can use a while loop to iterate until the number becomes zero. In each iteration, add the number n to the sum. This total sum is given as output.
sum_of_number <- function(n) {
if(n < 0) {
print("Enter a positive number")
} else {
sum = 0
# use while loop to iterate until zero
while(n > 0) {
sum = sum + n
n = n - 1
}
print(paste("The sum of numbers up to the given limit is", sum))
}
}
# n = as.integer(readline(prompt = "Enter a number: "))
# Set a number
n = 87
sum_of_number(n)
## [1] "The sum of numbers up to the given limit is 3828"
# Set a number
n = 12
sum_of_number(n)
## [1] "The sum of numbers up to the given limit is 78"
# Set a number
n = 109
sum_of_number(n)
## [1] "The sum of numbers up to the given limit is 5995"