Search code examples
algorithmdata-structurescomputer-sciencetiming

How many times is the process command repeated in the code snippet? Why?


This snippet of code is not related to a specific language and is actually about the effect of two four loops on the final result.

For(int i=0;i<n-i;i++)
  for(int i=0;i<n-i;i++)
    process;

How many time is the "process" command repeated in the code?
Why?


Solution

  • Lets assume that

    • For is a typo for for
    • process; is actually an allowed syntax for a statement
    • the inner int i creates a local variable which is not in conflict with the outer i
    • all inner i refer to the same variable

    Then the both loops will iterate until 2*i <= n, i.e. n/2 times, give or take 1 for odd n. Being nested and independent (see assumptions above) it will result in process; being executed (n * n) / 4 times.