Home > Software engineering >  Write a for loop that calculates the sum of numbers i to n in R
Write a for loop that calculates the sum of numbers i to n in R

Time:10-06

Im trying to write a loop that calculates the sum of the numbers 0:200. What I have come up with is just printing the sum, 200 times: Y <- 0:200 for(n in Y) {Y <- sum(Y) print(Y)} I want the loop to only return the value 20100 and it must be a for loop. Thanks!

CodePudding user response:

Something like that?

sum_i <- 0
for (i in 1:200) {
  sum_i <- sum_i   i
}

sum_i
[1] 20100
  • Related