Summation and Loop in R | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Summation and Loop in R

Hi everyone, I’m trying to write a code for the following prompt which asks me to use sum. I’m not sure what to do next in order to print the total number. Use a loop to calculate the sum of all numbers that are a multiple of 3 in the range of 1 to 1000. A number is a multiple of 3 if the remainder of dividing it by 3 is 0. My code: sum <- 0 for (x in 1:1000) { if (x%%3 == 0) {

30th Sep 2021, 12:39 AM
sophia.tr07
1 Answer
0
sum <- 0 for (x in 1:1000) { if (x%%3 == 0) { sum <- sum+x } print(sum) Every time you have a number divisible by 3, the x varible add to sum variable I hope this help you
1st Oct 2021, 12:52 AM
Cesar Torres
Cesar Torres - avatar