fastread homefastrread library fastread menu

R Programming : Find the Sum of Natural Numbers

Tutorial by:Maria Ghoste      Date: 2016-06-10 03:54:21

❰ Previous Next ❱

Source Code

# Program to find the sum of
# natural numbers upto n
# where n is provided by user

# 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.

We could have solved the above problem without using any loops. From mathematics, we know that sum of natural numbers is given by n*(n+1)/2. We could have used this formula directly. For example, if n = 10, the sum would be (10*11)/2 = 55.

❰ Previous Next ❱


R Programming

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website