Given an array of integers, write program to move all zeros at the end of the non zero elements.

  • Input : 1,0,2,0,3,0,0,4,5,6,7,0,0,0
  • Output : 1,2,3,4,5,6,7,0,0,0,0,0,0,0

Code:

        public  static void MoveZeroToEnd(int[] input)
        {
            Console.WriteLine(string.Join(",", input));
            int counter, jnonZeroIndex;
            counter = jnonZeroIndex = 0;
            int length = input.Length;

            for (counter = 0; counter < length; counter++)
            {
                if (input[counter] > 0)
                {
                    input[jnonZeroIndex] = input[counter];
                    jnonZeroIndex = jnonZeroIndex + 1;
                }
            }
            while (jnonZeroIndex < length)
            {
                input[jnonZeroIndex] = 0;
                jnonZeroIndex++;
            }
            Console.WriteLine(string.Join(",", input));

        }

Test

input Array : 1,0,2,0,3,0,0,4,5,6,7,0,0,0

Output Array : 1,2,3,4,5,6,7,0,0,0,0,0,0,0

input Array : 1,0,2,0,3,0,0,4,5,6,7,0,0,0,1,2,3,4,5,6,7,8,9,98

Output Array : 1,2,3,4,5,6,7,1,2,3,4,5,6,7,8,9,98,0,0,0,0,0,0,0