Find sum of natural numbers without/with formula using R Programming Languge

Find sum of natural numbers without/with formula using R Programming Languge

Without Formula:
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”

With formula:
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”

No Comments

Post a Reply