How to create and set values to a 3d array in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Function to initialize a 3D array
func InitializeArray(array [][][]int, x, y, z int) {
    for i := 0; i < x; i++ {
        for j := 0; j < y; j++ {
            for k := 0; k < z; k++ {
                array[i][j][k] = i + j + k // Initialization
            }
        }
    }
}

// Function to print a 3D array
func PrintArray(array [][][]int, x, y, z int) {
    for i := 0; i < x; i++ {
        for j := 0; j < y; j++ {
            for k := 0; k < z; k++ {
                fmt.Print(array[i][j][k], " ")
            }
            fmt.Println()
        }
    }
}

func main() {
    x, y, z := 2, 3, 4

    // Create a 3D slice dynamically
    array := make([][][]int, x)
    for i := range array {
        array[i] = make([][]int, y)
        for j := range array[i] {
            array[i][j] = make([]int, z)
        }
    }

    InitializeArray(array, x, y, z)
    PrintArray(array, x, y, z)
}


/*
run:

0 1 2 3 
1 2 3 4 
2 3 4 5 
1 2 3 4 
2 3 4 5 
3 4 5 6 

*/

 



answered Apr 21, 2025 by avibootz
...