-
Notifications
You must be signed in to change notification settings - Fork 690
/
PushZeroesToEnd.cs
50 lines (40 loc) · 1.36 KB
/
PushZeroesToEnd.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* C# program to push zeroes to back of array */
using System;
public class PushZeroAtEnd
{
// Function which pushes all zeros
// to end of an array.
static void ZerosToEnd(int []arr, int n)
{
// Count of non-zero elements
int count = 0;
// Traverse the array. If element encountered is
// non-zero, then replace the element
// at index â..countâ.. with this element
for (int i = 0; i <n; i++)
if (arr[i] != 0)
// here count is incremented
arr[count++] = arr[i];
// Now all non-zero elements have been shifted to
// front and â..countâ.. is set as index of first 0.
// Make all elements 0 from count to end.
while (count < n)
arr[count++] = 0;
}
public static void Main ()
{
Console.WriteLine("Enter Number of Elements in Array:");
string val;
val = Console.ReadLine();
int num = Convert.ToInt32(val);
int[] arr = new int[num];
Console.WriteLine("Enter Array Elements:");
int i;
for(i=0; i<num; i++)
arr[i] = Convert.ToInt32(Console.ReadLine());
ZerosToEnd(arr, num);
Console.WriteLine("Array after doing the operation: ");
for (i = 0; i <num; i++)
Console.Write(arr[i] +" ");
}
}