Open In App

Program to shift all zero to the end of array in Golang

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The task is to shift all the zeroes appearing in the array to the end of the array. In Golang, this can be done as follows:
Example: 

Input: 1 0 7 0 3

Output: 1 7 3 0 0

Go




// Golang program to shift all zero to the end of an array
package main
 
import (
    "fmt"
)
 
func main() {
 
    // Creating an array of tiny type
    // Using var keyword
    var ar [5]int
 
    // Elements are assigned using index
    ar[0] = 1
    ar[1] = 0
    ar[2] = 7
    ar[3] = 0
    ar[4] = 3
 
    // taking the length of array
    var arr_ele_number = len(ar)
    var last_non_zero_index = 0
 
    for i := 0; i < arr_ele_number; i++ {
 
        if ar[i] != 0 {
             
            ar[last_non_zero_index], ar[i] = ar[i], ar[last_non_zero_index]
            last_non_zero_index++
 
        }
    }
 
    fmt.Println("The array elements after shifting all zero to ends")
 
    for i := 0; i < arr_ele_number; i++ {
 
        fmt.Printf("%d ", ar[i])
 
    }
}


Output:

The array elements after shifting all zero to ends:
1 7 3 0 0 

Explanation: The logic behind the above example is that the user inputs the number of elements and the values of those elements. Then, the array is traversed while searching the zeroes and the zeroes are then shifted to the end of the array.
 


Last Updated : 23 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads