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

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
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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])
  
    }
}

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.