Home > Blockchain >  Sum even numbers without using while
Sum even numbers without using while

Time:12-09

I am stuck with a sum that I don't know how to solve this problem. I need to sum even numbers from 2 to 20, and this numbers sum 3.

n<-20
j<-0
for (i in 1:n) {
  if(i %% 2 == 0)
    j<-i 3
print(j)
}
Output:
[1] 0  
[1] 5  
[1] 5   
[1] 7  
[1] 7  
[1] 9  
[1] 9  
[1] 11  
[1] 11  
[1] 13  
[1] 13  
[1] 15  
[1] 15  
[1] 17  
[1] 17  
[1] 19  
[1] 19  
[1] 21  
[1] 21  
[1] 23   

With the function that I used I got the answer, but I don't know why it is repeated twice.

CodePudding user response:

Add curly braces:

for (i in 1:n) {
    if(i %% 2 == 0){
        j <- i 3
        print(j)
   }         
}

You can get the same outcome without using the loop:

vec <- 1:20

vec[vec %% 2 == 0]   3
  •  Tags:  
  • r
  • Related