Find sum of natural numbers without or with formula using R Programming Language

Explore the world of summing natural numbers in R! Uncover the beauty of mathematical formulas and calculations. For instance, the sum of the first n natural numbers can be expressed as n * (n + 1) / 2.

Delve into R programming to implement these methods and witness the elegance of combining mathematical concepts with coding.

# Sum of natural numbers without formula

R Program to find the sum of natural numbers without using a formula n <- 10

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: 4
[1] "The sum is 10"

# Sum of natural numbers with formula:

#R Program to find the sum of natural numbers using the formula n * (n + 1) / 2 n <- 10

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: 7
[1] "The sum is 28"
Scroll to Top