Advanced Iterative Loops and Code: Worked Time Complexity Examples

Trace changing steps and dependent bounds before naming a complexity class. Two complete examples show why similar nested loops can be Theta(n) or Theta(n log n).

KnowledgeGate Team

Exam prep & CS education

Updated 28 Nov 20266 min read
Advanced Iterative Loops and Code: Worked Time Complexity Examples

Ordinary single loops are easy to label, but trouble begins when a step changes, an inner bound depends on the outer variable, or an update squares its value. Then "nested means quadratic" fails: count first, check a small input, and only then classify the growth. For loop-phase order, Iterative Loops in C for GATE: Code Traces, Worked Examples and Exam Traps provides the foundation; nonlinear updates, geometric blocks and harmonic bounds require deriving the control-state sequence and summing its actual row costs. The GATE category connects this skill to surrounding preparation.

Advanced iterative loops: read the update and bound before counting

One iteration means one execution of the loop body. Before doing algebra, separate three questions:

  1. What values does the control variable actually take?

  2. How many times does the body run for each outer value?

  3. Does the problem ask for an exact count or only an asymptotic class?

An additive update such as i++ visits consecutive values. A multiplicative update such as i *= 2 visits powers of two. A nonlinear update such as i = i * i grows even faster. With dependent bounds, an inner loop may end at i or step by i, so its row length changes.

Nesting depth alone therefore does not determine complexity. Algorithm Analysis Basics: Operation Counts, Growth Rates and Worked Examples owns the cost-model foundation: name the counted event and separate exact totals from growth classes. Advanced loops add nonlinear states and dependent bounds. Derive their operation counts from code.

Additive, multiplicative and squaring loops: trace the actual states

Three loop tracks compare consecutive, doubling, and squaring states up to 256 with body counts and growth classes.

Compare three loops with the inclusive bound i <= 256.

  • For for (i = 1; i <= 256; i++), the body runs 256 times. For variable n, this family is Theta(n).

  • For for (i = 1; i <= 256; i *= 2), the executed values are 1, 2, 4, 8, 16, 32, 64, 128, 256. That is 9 body executions, giving Theta(log n).

  • For for (i = 2; i <= 256; i = i * i), the values are 2, 4, 16, 256. That is exactly 4 body executions.

For the squaring loop, number the first executed value with k = 0. Then i_k = 2^(2^k). The condition 2^(2^k) <= n implies 2^k <= log2 n, so k <= log2(log2 n). Including k = 0, the body-count family is Theta(log log n). Starting this update at 0 or 1 is a bug because squaring either value makes no progress.

Three loop tracks show additive, doubling, and squaring states up to 256 with their body counts.

Geometric blocks: a complete linear count for n = 20

Consider code that groups consecutive indices into blocks whose starting positions double:

c
int count = 0;
for (long long width = 1; width <= n; width *= 2) {
    for (long long j = width; j <= n && j < 2 * width; j++) {
        count++;
    }
}

For n = 20, the outer widths are 1, 2, 4, 8 and 16. Trace each block separately:

  • width = 1: j = 1, so 1 execution.

  • width = 2: j = 2, 3, so 2 executions.

  • width = 4: j = 4, 5, 6, 7, so 4 executions.

  • width = 8: j = 8 through 15, so 8 executions.

  • width = 16: j = 16 through 20, so 5 executions because n cuts the block short.

Therefore, count = 1 + 2 + 4 + 8 + 5 = 20.

The blocks are [1, 1], [2, 3], [4, 7], [8, 15] and [16, 20]. They are disjoint and together contain every integer from 1 through 20 exactly once. For arbitrary positive n, each power-of-two start width covers [width, min(n, 2width - 1)], so the blocks partition [1, n]. The exact body count is n and the tight bound is Theta(n), even though the code is nested and the number of outer states is Theta(log n).

Dependent step size: when nested loops produce a harmonic sum

Now change only the outer update:

c
int count = 0;
for (int i = 1; i <= n; i++) {
    for (int j = i; j <= n; j += i) {
        count++;
    }
}

The outer loop now visits every integer. For n = 8, the inner counts are floor(8/1), floor(8/2), ..., floor(8/8), which gives 8, 4, 2, 2, 1, 1, 1, 1. Their exact total is 8 + 4 + 2 + 2 + 1 + 1 + 1 + 1 = 20. A rectangular 8 x 8 count is wrong because each row has a different length.

In general, let H_n = 1 + 1/2 + ... + 1/n. The total S = sum from i = 1 to n of floor(n/i) satisfies nH_n - n <= S <= nH_n. Since H_n = Theta(log n), the tight bound is Theta(n log n). The geometric-block loop partitions a range and counts each index once. This loop samples every divisor step and produces a harmonic sum. That small change creates a different growth class. Asymptotic Notations Explained: Big O, Omega and Theta with Worked Examples owns the formal definitions and constant-threshold proofs; here those notations classify sums obtained directly from loop states.

A repeatable method for analysing unfamiliar iterative code

Use this five-step method:

  1. Write the exact control-variable sequence.

  2. Count the inner body for one fixed outer value.

  3. Express that per-state cost as f(i).

  4. Sum f(i) over the outer values actually visited.

  5. Check one exact small input, then simplify the sum to Theta.

Outer sequence

Inner cost

Exact n

Exact total

Growth

Blocks starting 1, 2, 4, 8, 16

length of [width, min(n, 2width - 1)]

20

20

Theta(n)

All integers 1..8

floor(8/i)

8

20

Theta(n log n)

Before any algebra, also check termination. The update must move every reachable state towards making the condition false. The squaring loop starting at i = 1 fails this check because 1 * 1 remains 1 forever.

Advanced iterative-loop traps and precise corrections

Shortcut

Why it fails

Correction

Multiply nominal bounds because loops are nested

Geometric blocks are disjoint

List the intervals and count their union

Treat width *= 2 as n/2 iterations

The sequence is geometric

List 1, 2, 4, 8, 16, giving 5 outer executions at n = 20

Replace every dependent row with its maximum

It creates a false rectangle

Sum 1 + 2 + 4 + 8 + 5 = 20

Drop floors in an exact-count question

Floors change the integer answer

Keep them until the exact total is complete

Confuse body executions with condition checks

The final failed check is not a body run

Name the quantity before counting it

Ignore a non-progressing update

The loop may never terminate

Test the update at every reachable special value

The geometric-block nest has 5 outer executions but exactly 20 count++ executions at n = 20. The all-integer version also has 20 executions at n = 8, yet its family is Theta(n log n), not Theta(n). The squaring loop runs 4 times at n = 256 only because it starts at 2. Floors and constant off-by-one terms usually do not change Theta, but they do change exact-output answers.

How advanced iterative loops are tested in code-tracing questions

Common question forms ask you to find a final counter value, select a tight asymptotic bound, compare similar-looking nests, detect non-termination, or choose an update that produces a target growth rate. Each form rewards the same discipline: list reachable states, name the counted event, and retain exact integer totals until the end.

For the geometric-block code at n = 20, the printed count is 20 and the tight answer is Theta(n). For the dependent-step version at n = 8, the exact count is also 20 but the family is Theta(n log n). The same exact output can arise from different mechanisms, so one trace alone never proves a complexity class.

Advanced iterative loops: the short version and next step

Trace the values, write the cost for each state, sum over the states actually visited, and only then classify the sum. At n = 20, the central example has five outer states, row counts 1, 2, 4, 8 and 5, exact total 20, and tight bound Theta(n).

For a structured path through the wider GATE CS syllabus, GATE Guidance by Sanchit Sir is the next step. Use it to place this loop analysis alongside the other subjects in your preparation.