Move all zeros to last/end in the array

Hey guys, Bushan here, welcome back to B2 Tech. Today in this article I will show you how to solve another Interview program using Java/C/C++ and Python. So without wasting anymore time let’s begin.



Problem Statement: Given an integer array, move/shift all the zeros in the array to the end of the array and return the array.

Test Cases:

Test Case – 1
Input: {1, 0, 2, 0, 3, 0 4}
Output: {1, 2, 3, 0, 0, 0}
Test Case – 2
Input: {0, 0, 4, 5, 0, 0}
Output: {4, 5, 0, 0, 0, 0}



JavaC++CPython
[java] import java.util.*;
public class ShiftAllZerosToLast
{
public static void main(String[] args) {
int a[] = {0, 0, 4, 0, 8, 0, 1};
System.out.println(Arrays.toString(shiftAllZerosToLast(a)));
}

public static int[] shiftAllZerosToLast(int a[]){
int j = 0;
for (int i = 0; i < a.length; i++){
if (a[i] != 0){
if (i == j){
j++;
} else{
a[j] = a[i];
a[i] = 0;
j++;
}
}
}
return a;
}
}
[/java]

[cpp] #include<iostream>
using namespace std;

int main()
{
int a[100];
int j = 0;
int i = 0;
int num = 0;

cout << “Enter the size of the array: “; cin >> num;

cout << “Enter the array values: “;
for(i = 0; i < num; i++){ cin>>a[i];
}

for(i = 0; i < num; i++){
if(a[i] != 0){
if(i == j){
j++;
}else{
a[j] = a[i];
a[i] = 0;
j++;
}
}
}
cout << “After shifting the zeros:”;
for(i = 0; i < num; i++){
cout << a[i] << “\n”;
}
return 0;
}
[/cpp]

[c] #include <stdio.h>

int main()
{
int a[100];
int j = 0;
int i = 0;
int num = 0;

printf(“Enter a size of the array: “);
scanf(“%d”, &num);

printf(“Enter the array values: “);
for(i = 0; i < num; i++){
scanf(“%d”, &a[i]);
}

for(i = 0; i < num; i++){
if(a[i] != 0){
if(i == j){
j++;
}else{
a[j] = a[i];
a[i] = 0;
j++;
}
}
}
printf(“After shifting the zeros:”);
for(i = 0; i < num; i++){
printf(“%d\n”,a[i]);
}
return 0;
}
[/c]

Tab content



About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *