Golang Program to insert an item into the array without using library function



An array in go language is defined as the data structure that is used to store elements in contiguous memory locations. Arrays allow us to search and store elements at constant times. arrays use the index to store elements that start from 0 and goes on to n – 1, where n is the length of the array.

Algorithm

  • Step 1 − First, we need to import fmt package.

  • Step 2 − Now, start the main() function. Inside the main() initialize an array of strings.

  • Step 3 − In order to add values to this array we have to mention the index to which we wish to store a particular value.

  • Step 4 − So, mention the index after the name of the array and assign the value to that index using equality operator.

  • Step 5 − In the same way store values to every index of the array. then we need to print the array.

  • Step 6 − To print the array use fmt.Println() function and mention each index that should be printed.

Example

In this example we will write a go language program to add values to an array of strings in the main() function. We will first initialize an array of strings of specific size and then add values to its every index.

package main
import "fmt"
func main() {

   // initializing an array
   var array [3]string

   // adding values to it
   array[0] = "India"
   array[1] = "Canada"
   array[2] = "Japan"

   // printing the array
   fmt.Println("The first element of array is:", array[0])
   fmt.Println("The second element of array is:", array[1])
   fmt.Println("The third element of array is:", array[2])
}

Output

The first element of array is: India
The second element of array is: Canada
The third element of array is: Japan

Conclusion

We have successfully compiled and executed and a go language program to insert an item into the array without using library functions.


Advertisements