Given an array of integers, {1,0,2,0,3,0,0,4,5,6,7,0,0,0}, Move all 0s at the end like (1,2,3,4,5,6,7,0,0,0,0,0,0,0}

#include <stdio.h>

void zeroatend(int a[], int n)
{
int i = 0, j = 0;

for(j = 0; j < n; ++j)
{
if(a[j])
a[i++] = a[j];
}

while(i < n)
a[i++] = 0;
}



int main()
{
int n;

scanf("%d", &n);

int a[n];
int i;

for(i = 0; i < n; ++i)
{
scanf("%d", a + i);
}

zeroatend(a, n);

for(i = 0; i < n; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
}
Advertisements

One thought on “Given an array of integers, {1,0,2,0,3,0,0,4,5,6,7,0,0,0}, Move all 0s at the end like (1,2,3,4,5,6,7,0,0,0,0,0,0,0}

  1. good logic but needs one improvement, after shifting all non-zero number to left you are putting zero till end of the array. It would be better if you can store the last "j" (suppose in k) where you shifted to left, and running while-loop till the last "j" (e.g. k).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s