How to iterate an array from the middle outward (stepping left and right alternately) in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func main() {

    // Array to iterate
    arr := []int{0, 1, 2, 3, 4, 5, 6, 7}
    n := len(arr)

    // Middle index for even-sized arrays
    mid := n / 2

    // Left starts before the middle, right starts at the middle
    left := mid - 1
    right := mid

    // Iterate outward from the middle
    for left >= 0 || right < n {

        if right < n {
            fmt.Print(arr[right], " ")
            right++
        }

        if left >= 0 {
            fmt.Print(arr[left], " ")
            left--
        }
    }
}


/*
run:

4 3 5 2 6 1 7 0

*/

 



answered Jun 29 by avibootz

Related questions

...