Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum even numbers without using while

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading