Program to shift all zero to the end of array in Golang
Last Updated :
23 Feb, 2022
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
package main
import (
"fmt"
)
func main() {
var ar [ 5 ]int
ar[ 0 ] = 1
ar[ 1 ] = 0
ar[ 2 ] = 7
ar[ 3 ] = 0
ar[ 4 ] = 3
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...