How to find the length of a For loop? Here is a simple example:
For[i = 0, i < 4, i++, Print[i]]
0
1
2
3
How to find that there are in total 4 outputs using the //Length function or similar.
Let me take an example for comparison:
tb = Table[x, {x, 1, 5, 1}]
Length[tb]
5
The problem is that I have long For loop defined which is almost impossible to copy here, bcz its too complicated. There is an iteration
i = 0, i < 4, i++, Print[i]
defined inside the For loop. The actual problem in fractional, not integer as in the example above. I want know what is the length of the range between i = min and i = max just like we use "Length" for a table as shown above.
In the example above, obviously its 4, but how can we ask mathematica to find total number of outputs such as 4 for us.

i = 0, i < 4, i++. Surely you're asking something more than that, but I'm not sure what. – lericr Oct 11 '22 at 20:49Forand you could ask that question for any code. If you are asking how to programmatically get the number of iterations of aForloop that is held usingHold, then if the same structure as the one in the example you provided is being used, then one could use for exampleHold[For[i = 0, i < 4, i++, Print[i]]][[1, 2, 2]]. The reason for the part choice can be visualized usingFor[i = 0, i < 4, i++, Print[i]] // Hold // TreeForm. – userrandrand Oct 11 '22 at 20:52iafter the loop is finished, and determine the number of iterations that way. – lericr Oct 11 '22 at 20:54For[i = 0; counter = 0, i < 10, i += 3; counter++, Print[i]]. I altered your example to have a case where the loop iterator didn't increment by one, and therefore doesn't reflect the number of iterations. When the loop is done, just inspectcounter. – lericr Oct 11 '22 at 20:59Doinstead ofFor(in which case the code I provided before does not work). To see whyDois preferred there is this answer – userrandrand Oct 11 '22 at 20:59(Length@Trace[For[...], TraceDepth -> 3] - 4)/3? If you want to predict the number of iterations, I doubt that is possible, since one may advanceiin the body according to whatever condition, evenWeatherData[First@CityData["Kathmandu"], "Temperature"]. – Michael E2 Oct 11 '22 at 22:21i = 0, i < 10, i+=.25, then the total number of iterations is 40. If you don't want to calculate manually, then the formula would beCelling[(max - min)/stepsize]. Or, if you want to do it while the for loop is running, use thecounteridea I posted above. – lericr Oct 11 '22 at 22:22output = {}; For[i = 0, i < 4, i++, AppendTo[output, i]]. Thenoutputwould be{0, 1, 2, 3}, and you can just apply Length to it. – lericr Oct 11 '22 at 22:27Reap[For[i = 0, i < 4, i++, Sow[i]]]. This gives{Null, {{0, 1, 2, 3}}}from which you can extract the "output" and check its length. – lericr Oct 11 '22 at 22:29Internal`GetIteratorLength[{i, 0, 4}]assumes <=, not <. AndInternal`GetIteratorLength[{i, 0, 4, 0.25}] - 1won't always work either. – Michael E2 Oct 11 '22 at 22:33