Move 0’s to end of array

Write a program to Move 0’s to end of array
For example:

Input:
Arr = { 9, -4, 0, 1, 0, 0, 7, 0 }

Output:
9, -4, 1, 7, 0, 0, 0, 0

Solution:


using System;
using System.Linq;

namespace MoveArray
{
    class Program
    {
        static void Main()
        {

            var arr = new[] { 9, -4, 0, 1, 0, 0, 7, 0 };

            var result = new int[arr.Length];//Initialize array with default value as 0

            var pos = 0;

            foreach (var t in arr)
            {

                if (t != 0) result[pos++] = t;
            }

            Console.Write($"Reverse array: {string.Join(", ", result)}");
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *