Output:
Click Here For Java Online Compiler
Solution:
*** Move Zeros Of An Array To Front *** Given array is: 1, 0, 2, 0, 3, 0, 4, 0, 5, Now it becomes: 0, 0, 0, 0, 1, 2, 3, 4, 5,
Click Here For Java Online Compiler
Solution:
public class MoveZerosToFront { static void moveZerosToFront(int inputArray[]) { int counter = inputArray.length - 1; for (int i = inputArray.length - 1; i >= 0; i--) { if (inputArray[i] != 0) { //Assigning inputArray[i] to inputArray[counter] inputArray[counter] = inputArray[i]; //Decrementing the counter by 1 counter--; } } //Assigning 0 to remaining elements while (counter >= 0) { inputArray[counter] = 0; counter--; } System.out.print("Now it becomes: "); for (int i = 0; i < inputArray.length; i++) { System.out.print(inputArray[i] + ", "); } } public static void main(String[] args) { int array[] = {1, 0, 2, 0, 3, 0, 4, 0, 5}; System.out.println("*** Move Zeros Of An Array To Front ***" + "\n"); System.out.print("Given array is: "); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + ", "); } System.out.println(); moveZerosToFront(array); } }
comment 0 comments:
more_vertsentiment_satisfied Emoticon