programming
for-loop
iteration
looping
code duplication

Get loop count inside a for-loop

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Getting the loop count inside a for loop sounds trivial, but the right pattern depends on what “count” means in that context. Sometimes you want the zero-based index, sometimes a one-based display number, and sometimes the count of items actually processed after filtering. Using the language’s built-in iteration tools is usually clearer and safer than maintaining your own counter variable.

Distinguish Index From Processed Count

The first thing to clarify is whether you need:

  • the current iteration index
  • a display counter starting at 1
  • a count of items that passed a condition

Those are not always the same number.

For example, if a loop skips some items with continue, the iteration index still advances while the processed-item count may not.

Classic for Loops Already Expose the Index

In C-style languages, the counter is usually part of the loop syntax.

java
for (int i = 0; i < 5; i++) {
    System.out.println("index=" + i);
}

This is the simplest answer when you control the loop bounds directly. The main risk is off-by-one mistakes from mixing zero-based indexes with one-based display values.

Python: Use enumerate

In Python, enumerate is the idiomatic way to get both the index and the value.

python
1names = ["Ada", "Linus", "Grace"]
2
3for index, name in enumerate(names):
4    print(index, name)

If the loop count should start at 1, pass start=1.

python
for number, name in enumerate(names, start=1):
    print(number, name)

This is almost always better than writing i = 0 outside the loop and incrementing it manually.

JavaScript and C# Have Similar Helpers

JavaScript arrays expose .entries() for index-value pairs.

javascript
1const items = ["a", "b", "c"];
2
3for (const [index, value] of items.entries()) {
4  console.log(index, value);
5}

In C#, a normal for loop is direct, while LINQ can help when you want index and value in a foreach style.

csharp
1var values = new[] { "x", "y", "z" };
2for (int i = 0; i < values.Length; i++)
3{
4    Console.WriteLine($"{i}: {values[i]}");
5}

The principle is the same: use the language feature that already models index plus value.

Count Processed Items Explicitly When Filtering

If some loop iterations are skipped, index and processed count diverge. Handle that explicitly.

python
1values = [10, 15, 20, 25]
2processed = 0
3
4for index, value in enumerate(values):
5    if value % 20 != 0:
6        continue
7    processed += 1
8    print(f"index={index}, processed={processed}, value={value}")

Here index tells you where the item came from, while processed tells you how many matching items have been handled.

That distinction prevents subtle logging and progress-report bugs.

Prefer No Counter When You Do Not Need One

A lot of code asks for “the loop count” out of habit, not necessity. If you only need the elements, iterate over the elements directly.

Cleaner loops are less error-prone because there is no indexing logic to get wrong. Use a counter only when position actually matters, such as:

  • aligning values across arrays
  • writing results back by position
  • reporting progress to users
  • formatting numbered output

Common Pitfalls

  • Mixing zero-based indexes and one-based display numbers.
  • Using a manual counter when the language already provides an index helper.
  • Confusing loop index with count of processed items after filtering.
  • Reusing generic names like i and j in complex nested loops where clearer names would reduce mistakes.

Summary

  • Decide whether you need index, display count, or processed-item count.
  • Use the built-in loop counter in classic for loops.
  • In Python, prefer enumerate over manual counters.
  • Keep a separate processed count when filtering changes the effective total.
  • If position does not matter, avoid a counter entirely.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions