brittAnderson / Intro2Computing4Psychology

A guided introduction to computing tools useful for research in psychology - targeted to complete beginners
46 stars 159 forks source link

Printing only even numbers in a loop #72

Closed WisamAlkheder closed 2 years ago

WisamAlkheder commented 2 years ago

Hi everyone,

I'm having trouble figuring out how to only print the even numbers in a for loop seq.

I was able to do this:

`> for(i in seq(1:10)){

And I can produce an answer whether the number is even or odd (true or false).

How do I limit the printing to the even numbers though? without having to show the rest of the numbers (or zeros).

Best, Wisam

MohanpreetS commented 2 years ago

You can use an if statement to check if the number is even, and write a print command in the body of that if function.That would print only the even numbers. Also , when you write " i %%2 " you just calculate the mod value(remainder) when "i" is divided by 2, you also need to check if thats equal to 0 to make sure "i" is even

brittAnderson commented 2 years ago

Thanks Mohanpreet. If this is still not clear come to class tomorrow and we can go through it.

WisamAlkheder commented 2 years ago

Thank you, Mohan and Dr. Anderson. See you in class.