How to print array elements in groups of 2 with Go

1 Answer

0 votes
package main

import "fmt"

func main() {
    arr := []int{1, 2, 3, 4, 5, 6, 7}

    for i := 0; i < len(arr); i += 2 {
        if i + 1 < len(arr) {
            fmt.Printf("Group: %d, %d\n", arr[i], arr[i + 1])
        } else {
            // Handle the last element if the array length is odd
            fmt.Printf("Group: %d\n", arr[i]) 
        }
    }
}



/*
run:

Group: 1, 2
Group: 3, 4
Group: 5, 6
Group: 7

*/

 



answered Jun 21, 2025 by avibootz
...