Google+ Program For Move all zeroes to end of Array - CodieeHome
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
__

Moving All Zeros to End of Array

Goal: Program for moving all zeros to end of array.

Method-Used: Simple Logic.

Explanation: I tried this program with following three different methods:

 1.Traverse complete  array and increase count when you find any non zero element.After that do indexing of new array according to your count value.

2. Traverse complete array like when you find any non zero element ,store it ,increase count simultaneously and fill all remaining index of array with zero.

3.Traverse complete array like when you find any non zero element ,store it and assign zero to current index.

Among all three cases i found that  3rd case will give us minimum lines of code or have run time smaller than others.

So logic of third method is implemented in given program.

Program:

#include<iostream>

using namespace std;

#include<conio.h>

int main()

   {

    int a[10],count=0,n,i;

    cout<<"\n\tHow many elements you want to enter\n\t";

    cin>>n;

    cout<<"\n\tEnter Elements:\n";

    for(i=1;i<=n;i++)

    {

    cout<<"\t";

      cin>>a[i];

      

    }

    for(i=1;i<=n;i++)

     {

      if(a[i]!=0)

      {

       a[count++]=a[i];

       a[i]=0;

                }

 }

     cout<<"After Moving all zero at last array is:\n";

     for(i=0;i<n;i++)

    {

      cout<<"\t"<<a[i];

    }

    getch();

    return 0;

       }

Output:


 If you want to share more information about topic discussed above or find anything incorrect Please do comments.  


0 comments:

Post a Comment

 
Top