Adsense 728 * 15

Search

Custom Search

Write a Program to Move all Zeros at The End of an Array


Given an array, Move all the zero element of an array at the end.

For example- Given array is

Input

int arr[] = {1,6,0,3,8,9,0,2};


Output

 // Move all zero at the end

int arr[] = {1,6,3,8,9,2,0,0};
   

Logic of a Program

Traverse an array and push all non-zero element in an array. Maintain the count. After traversing an array all no-zero element has been moved, now push all zero at the end.


Program to Move all Zeros at The End of an Array


#include <stdio.h>
#include <string.h>

main()
{
   int arr[] = {1,6,0,3,8,9,0,2};
   int i,count=0;
   
   int n = sizeof(arr)/sizeof(arr[0]);
   
   // Push all non-zero element
   for(i=0;i<n;i++){
       if(arr[i]>0){
       arr[count++]=arr[i];
       }
   }
   
   // At the end push all zero element
   while(count<n){
       arr[count++]=0;
   }
   
   for(i=0;i<n;i++){
       printf("%d",arr[i]);
   }
}



No comments:

Post a Comment