Pushing all the zero to the end in an array.

Question (Asked by Amazon ) :- Given a number in an array form, Come up with code to push all the zeros to the end.

Solution :-

#include<iomanip>
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int arr[20];
int len,count=0;
int i=0,n;
cout<<"Enter the size of array:-"<<endl;
cin>>n;
cout<<"enter elements:-"<<endl;
for(int i=0;i<n;i++)
{
cout<<" ";
cin>>arr[i];
}
cout<<"You've Entered :-"<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
//--------------sorting------------------
for(int i=0;i<n;i++)
{
if(arr[i] != 0)
arr[count++]=arr[i];
}
while(count<n)
{
arr[count++]=0;
}
cout<<endl<<"Now after pushing all the zeros to the end array is:-"<<endl;
for(int i=0;i<n;i++)
{
cout<<" "<<arr[i];
}
cout<<"nn"<<setw(30)<<"@ myprogworld..!! ";
getch();
return 0;
}

Output :-

Untitled

Leave a comment