To move all zero at right side of array

Question - 
Given an array, we have to more all zeros at right side of the array without change its order.
Example - 
Input : arr[] = {1, 2, 0, 3, 0}
Output : {1, 2, 3, 0, 0}
Approach - 
We store all non zero number in array with first position and after this we store all zeros at last of the array.
Implementation - 
//move all zero at right side of array
#include<iostream>
using namespace std;
void print(int arr[],int n)
{
    for(int i=0;i<n;i++)
        cout<<arr[i]<<", ";
}
void movezero(int arr[],int n)
{
    int count=0;
    for(int i=0;i<n;i++){
        if(arr[i]!=0){
            arr[count]=arr[i];
            count++;
        }
    }
    for(int i=count;i<n;i++)
    arr[i]=0;
}
int main()
{
    int n;
    cout<<"Enter number of elements : ";cin>>n;
    int arr[n];
    cout<<"Enter elements : "<<endl;
    for(int i=0;i<n;i++)
        cin>>arr[i];
    movezero(arr,n);
    print(arr,n);
    return 0;
}
Time complexity - O(n)
Extra space - O(1)

Comments