 # 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

```                                          ```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
 "The sum of numbers up to the given limit is 55"```
VIEW ALL
VIEW ALL
##### OtherTutorials
VIEW ALL 