R Program to find sum of natural numbers


February 5, 2023, Learn eTutorial
2193

How to find the sum of natural numbers?

Natural numbers are the whole numbers that occur naturally from 1 to n. these are also called cardinal numbers because they are used for counting. we can calculate the sum of natural numbers 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. 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

                                          n = as.integer(readline(prompt = "Enter a number: "))
if(n< 0) {
print("Enter a positive number")
} else {
sum = 0
# use while loop to iterate until zero
while(n > 0) {
sum = sum + num
n = n - 1
}
print(paste("The sum of numbers up to the given limit is", sum))
}
                                      

OUTPUT

Enter a number: 10
[1] "The sum of numbers up to the given limit is 55"