0
How to analyze that how much times a loop has been executed? How can we create logic?
2 Answers
+ 5
Put a logger inside your loop, run the code.
The amount of times the logger has printed out == no of times loop ran.
Or increment a variable by each time it runs,
print the variable when the loop ends.
+ 3
If you have one loop, you can likely figure it out by looking at it.
for (int i = 0; i <= 25; i += 2){}
i would run 26 times had it of been i++.
Since its i += 2, we just divide it by 2.
So, it will run 13 times.
Maybe it gets tough when you get to something like this:
for (int i = 0; i < 15; i++)
for (int k = 0; k < 3; k++)
for (int w = 0; w < 9; w += 2)
{}
How can we easily figure out how many times this will run, without debugging?
Well, how many times does each loop run individually?
The w loop runs 9 / 2 times.
= 5 (Rounds up).
The k loop runs 3 times
The i loop runs 15 times.
Now, since an inner loop must finish before the outer loop moves to the next itteration, we can multiply those numbers to get our result:
(This is how I would do the multiplication if I have not memorized what 15 * 15 was)
15 * 3 * 5 =
15 * 15 =
150 + (5 * 15) =
150 + (50 + 25) =
225
Those loops will run 225 times.
We'll try one more to make sure you get the idea:
for(int i = 2; i < 12; i += 5)
for (int k = 0; k <= 10; k += 3)
{}
k loop runs 11 / 3 times
= 4 (Rounds up)
i loop runs 10 / 5 times
= 2
**Note** If the increase to the variable is to large (or small), you may not get an extra itteration. Meaning, sometimes you could have to round down. **
So, 4 * 2 = 8.
Those loops run 8 times.
The point is there's a mathematical trick to finding out how many times the loop runs.