Shifting all the Zeros to End of Array through C Code in Linux.

   C Linux Code to shift all the zeros to the end of an array.
   1.Traverse through the array
   2.copy the non zero element to new array say result and increment the count
   3.fill the remaining array index with zeros

#include<stdio.h>
#include<stdlib.h>

int* zeroshift(int *, int);
int main()
{
    int size,i,j;
    int arr[]={1,2,0,3,4,0,0,6};
    size=sizeof(arr)/sizeof(int);
    int* ptr=zeroshift(arr,size);
    printf("After Shifting zeroes array is:\n");
    for(i=0;i<size;i++)
        printf("%d ",ptr[i]);
    printf("\n");
    return 0;
}

int* zeroshift(int *arr,int size)
{
    int i;
    int count=0;
    int *result=(int *)malloc(size*sizeof(int));
    for(i=0;i<size;i++)/* 1.Traverse through the array*/
    {
        if(arr[i]!=0)
        {
            result[count]=arr[i];/*2.copy the non zero element to new array say result and increment the count*/
                count++;
        }

    }
    //3.fill the rmaining array index with zeros
    for(i=count;i<size;i++)
    {
        result[i]=0;
        i++;
    }
    return result;
}
/*
   After Shifting zeroes array is:1
   2 3 4 6 0 0 0
 */

No comments:

Post a Comment