Skip to content
Related Articles

Related Articles

Improve Article
Program to shift all zero to the end of array in Golang
  • Last Updated : 10 May, 2020

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




// Golang program to shift all zero to the end of an array
package main
  
import (
    "fmt"
)
  
func main() {
  
    var c int
  
    // 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)
    c = 0
  
    for i := 0; i < arr_ele_number; i++ {
  
        if ar[i] != 0 {
  
            ar = ar[i]
  
            c = c + 1
  
        }
    }
  
    // Filling the remaining array
    // count index to zero
    for c != arr_ele_number {
  
        ar = 0
  
        c = c + 1
  
    }
  
    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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :