0
$\begingroup$

I am wondering if For could be used with multiple conditions (tests). For the simple example For[i = 0, i < 4; i > 0, i++, Print[i]] which prints 0, 1, 2, 3, is it possible to add another condition EvenQ[i] such that it only prints 0 and 2?

I tried For[i = 0, i < 4 && EvenQ[i], i++, Print[i]] which seems natural but does not work. Can anyone explain?

$\endgroup$
  • $\begingroup$ Your test i<4 && EvenQ[i] is a stopping condition, so the For loop stops after $i=0$. $\endgroup$ – Carl Woll Jan 23 '18 at 18:38
  • 1
    $\begingroup$ a;b always evaluates to b. Thus writing i < 4; i > 0 is the same as writing i > 0. Your first example doesn't really make sense. The second prints 0 because when i==1, EvenQ[i] evaluates to False, thus the loop stops. $\endgroup$ – Szabolcs Jan 23 '18 at 18:43
  • $\begingroup$ why not use i += 2 for the increment? $\endgroup$ – george2079 Jan 23 '18 at 19:19
  • $\begingroup$ @Szabolcs, thank you. Sorry in the first example I meant without ;i>0. But your pointing that out does answer another question of mine as if i < 4; i > 0 is actually two simultaneous conditions. I will take your comment as the answer. $\endgroup$ – nanjun Jan 23 '18 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.