R Program to Find the Sum of Natural Numbers

In this example, you'll learn to find the sum of natural numbers entered by the user. The example uses a while loop to calculate the sum.

To understand this example, you should have the knowledge of the following R programming topics:


Example 1: Find sum of natural numbers without formula

# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))

if(num  0) {
        sum = sum + num
        num = num - 1
    }

    print(paste("The sum is", sum))
}

Output

Enter a number: 10
[1] "The sum is 55"

Here, we ask the user for a number and display the sum of natural numbers upto that number.

We use while loop to iterate until the number becomes zero. On each iteration, we add the number num to sum, which gives the total sum in the end.

We could have solved the above problem without using any loops using a formula.

From mathematics, we know that sum of natural numbers is given by

n*(n+1)/2

For example, if n = 10, the sum would be (10*11)/2 = 55.


Example 2: Find sum of natural numbers using a formula

# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))

if(num 

Output

Enter a number: 10
[1] "The sum is 55"
Did you find this article helpful?