R Program to find sum of natural numbers

How to find sum of natural numbers

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

How sum of natural numbers is implemented in R Program

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.

ALGORITHM

  • STEP 1 : prompting appropriate messages to the user
  • STEP 2 : take user input using readline() into variables n
  • STEP 3 : use while loop to iterate until the n becomes zero.
  • STEP 4 : in each iteration, we add the number n to sum as sum = sum + n
  • STEP 5 : set n = n - 1
  • STEP 6 : print the sum as output

R Source Code

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"