R Program to Find the Sum of Natural Numbers


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) {
    print("Enter a positive number")
} else {
    sum = 0

    # use while loop to iterate until zero
    while(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 < 0) {
    print("Enter a positive number")
} else {
    sum = (num * (num + 1)) / 2;

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

Output

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

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges