Java code to move all zero of an integer array to the end of the array
source link: http://adnjavainterview.blogspot.com/2019/09/java-code-to-move-all-zero-of-integerto-endofarray.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Monday, 9 September 2019
Java code to move all zero of an integer array to the end of the array
For example,
Input array is = {2,1,0,3,5,0,9,0}
Output array is = {2,1,3,5,9,0,0,0}
package com.example.demo; public class ZeroNonZerosSeparate { public static void main(String[] args) { int[] nums = {2,1,0,3,5,0,9,0}; int index = 0;
for (int i = 0; i<nums.length; i++) { if (nums[i] != 0) { nums[index] = nums[i]; index++; } } while (index < nums.length) { nums[index] = 0; index++; } for (int i = 0; i<nums.length; i++) { System.out.print(nums[i]+" "); } } }
Output:-
2 1 3 5 9 0 0 0
Related Posts:-
1) Difference between NoClassDefFoundError and ClassNotFoundException in Java
2) Swap two variables without using third variable in Java
3) Sort a binary array using one traversal in Java
4) Java program to find second largest number in an array
5) Java Code to Print the Numbers as Pyramid - Examples
6) Java Program to find the Missing Number in an Array
7) Java program to print the first n prime numbers
8) Write a Java program to print the Floyd's triangle
No comments:
Post a Comment
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK