+ 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) {
1 Antwort
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