# counting number of outputs in For loop

I am using For loop and If within it. For example:

For[a=0, a < 21, a = a + 1,
If[EvenQ[a], Print[a,"\n"]]
]


Certainly, the program will print all even numbers below 21 starting from 0. I would like to Print the output along with counting number, like:

1. 0
2. 2
3. 4


etc.

I will be glad if you suggest me some command for the same.

• A good programming language offers a step width different from 1 in a for loop. For[a=0, a < 21, a = a +2, You will not need If[EvenQ[a] then. – Uwe Aug 1 '16 at 13:53
• I agree with you. But I need this counting in a more involved program. Thanx btw. – user31694 Aug 1 '16 at 17:20
• @J. M. Thank you for editing it look much better. – user31694 Aug 1 '16 at 17:24

## 2 Answers

i = 1;
For[a = 0, a < 21, a = a + 1, If[EvenQ[a], Print[i++, ". ", a]]]

1. 0
2. 2
3. 4

(and so on)

Another style of coding for your consideration:

Cases[Range[0, 21], _?EvenQ]

TableForm[%, TableHeadings -> Automatic]


See also Sow and Reap, e.g. Creating a table/Matrix during a For loop

• I would have used Select[Range[0, 21], EvenQ] instead. – J. M. will be back soon Aug 1 '16 at 12:18
• Why not cut to the chase: Range[0, 21, 2]? – Michael E2 Aug 1 '16 at 12:18
• @Michael, that would have corresponded to the OP using a += 2 in his/her loop. – J. M. will be back soon Aug 1 '16 at 12:25
• @J.M. Yes, that's cleaner. On the other hand _?EvenQ introduces the concept of pattern matching which may serve the OP. – Mr.Wizard Aug 1 '16 at 12:33
• @MichaelE2 I fear that would reduce the contrived example a bit too much to be instructive. – Mr.Wizard Aug 1 '16 at 12:33

I suggest reading this Q and A: Alternatives to procedural loops and iterating over lists in Mathematica as it is instructive and useful.

Just some variants to illustrate Sow and Reap and MapIndexed:

Reap[(i = 1;
For[a = 0, a < 21, If[EvenQ@a, Sow[{i++, a}]]; a = a + 1])][[-1,
1]] // TableForm


or

(i = 1); Range[0, 21] /. {x_?EvenQ :> {i++, x},
x_?OddQ :> Sequence[]} // TableForm


or

MapIndexed[{#2[[1]], #1} &, Range[0, 21, 2]] // TableForm


There are many ways to do things. That is part of the fun.

• Also i = 1; Cases[Range[0, 21], x_?EvenQ :> {i++, x}] // TableForm – Mr.Wizard Aug 1 '16 at 12:36
• @Mr.Wizard thank you, yes...I only posted really to illustrate Reap and Sow for this example as well as hyperlink to loop alternatives...and some ways to 'count'...like your comment:) – ubpdqn Aug 1 '16 at 12:40