A friend of mine shared the following code snippet with me and asked me to guess how many times the loop will run on average:
for(int i = 0; i < Random(1, 100); i++);
I tried to guess the answer analytically and gussed ~50 but the empirical test was surprising to me. Can someone explain why the average is around 12?
Runnable code: https://replit.com/@aalhour/RandomLoop#main.py
EDIT: Formatting.
So, it’s 1% that the loop ends at i = 1, if it takes that hurdle 2% that it ends at i = 2, if it takes that hurdle 3% that it ends at i = 3, etc.
The calculation is easier if you phrase that this way:
It’s 99% that the loop continues at i = 1, if it takes that hurdle 98% of the rest that it continues at i = 2, if it takes that hurdle 97% that it continues at i = 3, etc.
So, the probability to make it past i = n is
Note that this isn’t necessarily the case in all languages. Pascal, for example, has a real for loop where the limit is evaluated once and the index variable cannot be changed inside the loop, so that the compiler can determine the number of iterations before starting the first iteration.