# Code Smell 219 - Looping from index 0

> TL;DR: Start counting from one instead of zero. Like humans do.

# Problems

* [Bijection](https://maximilianocontieri.com/the-one-and-only-software-design-principle) from real-world broken
    
* Cognitive load
    
* Overly implementation-oriented code
    

# Solutions

1. Favor high-level declarative languages
    

# Context

Low-level languages force you to think at a machine level.

Hardware turning machines were designed to use binary gates and start indexing at 0.

A few programming languages use one-based indexing, where indexing starts from 1.

These languages are known for being higher level and more declarative:

* Basic / Visual Basic
    
* Pascal
    
* Smalltalk
    
* Fortran
    
* Lua
    
* MATLAB
    
* R
    
* Julia
    

# Sample Code

## Wrong

```go
package main

import "fmt"

func main() {    
    numbers := []int{10, 20, 30, 40, 50}
    
    for i := 0; i < len(numbers); i++ {
        // Iteration goes from zero to len-1
        fmt.Println(numbers[i])
    }
}
```

## Right

```plaintext
numbers = [10, 20, 30, 40, 50];

% Looping through the array using one-based indexing
% from 1 to length
for currentIndex = 1:length(numbers)
    disp(numbers(currentIndex));
end
```

# Detection

\[X\] Automatic

This is a language smell.

# Exceptions

* Low-level optimized code
    

# Tags

* Declarative Code
    

# Conclusion

We need to think as humans when we code and not as machines.

Humans count from one.

[Zero number](https://en.wikipedia.org/wiki/0) was a brilliant discovery in math and science but it does not apply to everyday counting.

# Relations

%[https://maximilianocontieri.com/code-smell-53-explicit-iteration] 

%[https://maximilianocontieri.com/code-smell-123-mixed-what-and-how] 

# More Info

[Wikipedia](https://en.wikipedia.org/wiki/Zero-based_numbering)

# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Andy Kelly](https://unsplash.com/@askkell) on [Unsplash](https://unsplash.com/photos/0E_vhMVqL9g)

---

> Pay attention to zeros. If there is a zero, someone will divide by it.

*Cem Kaner*

%[https://maximilianocontieri.com/software-engineering-great-quotes] 

---

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code] 

---

My new book about clean code is available for pre-order.

You will find several recipes like this one with a higher level of detail

[![Book](https://cdn.hashnode.com/res/hashnode/image/upload/v1690157075463/9539a4d6-ea40-4d33-b26b-bb085125a358.jpeg align="left")](https://amzn.to/44s1XdO)
