Move All Zeroes to End of Array in C#

Hello programmers,here is the article to move all zero in the last position of array. inside the program i am going to use two for loops and one while loop and one if statement. the concept of the code ,when non zero find in array,no any changes going to to happen. if zero find by filtering if statement then array remain same.when while execute then it fill all zero.lets see the codes.

Input and Output Screen

Code Explanation :
step 1: if you debug/run the program then control goes to Main method thereafter that go
inside of the Main.
step 2: inside Main i have taken integer array type variable arr. it has elements
{ 3, 2, 0, 4, 0, 8, 5 };
step 3: one more variable cnt. It initialize with 0.
step 4: next control go to for loop. for(int i = 0; i < arr.Length; i++).
i.e for(int i = 0; 0 <= 7; i++) here for loop condition.control move to inside.

step 5: the above for loop condition true. so condition move to if statement. if(arr[i]!=0).
if(arr[0]!=0). if(3!=0).if(true)
step 6: if condition true.then arr[cnt] = arr[i];i.e arr[0] = arr[0];so , 3 = 3
no array index value change. cnt = 0+1=1. for loop continue, i also increase.
step 7: i++. i = 1. 1<=7.true. if(arr[i]!=0) if(arr[1]!=0). if(2!=0).if(true). condition true.
step 8: like this for loop condition until condition false.
step 9: when control moves to while loop then first it check the condition.
when condition true then array index it puts zeroes values.
step 9: now then control moves to down of for loop and Console.Write(arr[i]);
it prints all array you can see zero moves to last position of array index.

Happy coding … thanks.

Post Author: adama