# 18. For

### For Statement

When we need to repeat things, that's where loops come into play. Unlike other programming languages, Go has only single construct for looping, **`for`**

### Traditional loop

We can write traditional for loop using loop variable similar to most other programming languages.

`for initialization; condition; post statement {`&#x20;

`code to execute`&#x20;

`}`

{% code title="main.go" %}

```go
for i := 1; i < 10; i++ {
    fmt.Printf("Hello %d \n", i)
}
```

{% endcode %}

### For loop as while loop

We can only define the condition part in for loop and it will act like a while loop. We need to make sure initialization if any required as well as post conditioned are handled.

`for condition { code to execute }`

{% code title="main.go" %}

```go
j := 1
for j < 10 {
	fmt.Printf("Hello %d\n ", j)
	j = j + 1
}
```

{% endcode %}

If we skip the line 4 above, we end up creating infinite loop.

### Continue and Break

We can use continue and break statement inside of for loop to control flow.  `continue` is used to run next iteration of loop and abandon remaining code in current loop iteration. `break` is used to break out of the loop.

{% code title="main.go" %}

```go
for k := 1; k < 20; k++ {
	if k%2 == 0 {
		continue
	}
	fmt.Printf("Hello  %d\n", k)
}
for k := 1; k < 20; k++ {
	if k == 13 {
		break
	}
	fmt.Printf("Hello  %d\n", k)
}
```

{% endcode %}

The first for loop above will not print if value is even and continue to next iteration. Second for loop will break the loop when k reaches 13.

### Infinite Loop

We can also skip condition part of for loop which will create infinite loop. Make sure there is way to break out of for loop when no condition is provided.

{% code title="main.go" %}

```go
for {
    fmt.Println("Hello!")
    // break based on some condition to exit infinite loop
}
```

{% endcode %}

### Iterating over range

Go can easily iterate over arrays,maps and slices using `range` keyword.

When iterating over slice, range returns index and value from slice.

{% code title="main.go" %}

```go
data := []string{"a", "b", "c"}
for index, value := range data {
	fmt.Println(index, value)
}
```

{% endcode %}

When iterating over maps, range returns key and value.

{% code title="main.go" %}

```go
capitals := map[string]string{
	"India":   "Pune",
	"England": "London",
	"U.S.":    "Washington",
}
for key, value := range capitals {
	fmt.Println(key, value)
}
```

{% endcode %}

range is also useful for getting each rune from string.

{% code title="main.go" %}

```go
greetings := "नमस्कार"
for _, char := range greetings {
	fmt.Printf("%c\n", char)
}
```

{% endcode %}
