Advertisements
Advertisements
Question
Write a program for the following.
Create an array ZR[] of type int and size 10 and fill it with variables. Create another array NZR[ ] that contains only the non zero elements of array ZR[ ].
For example:
| Input | ZR[ ] | 100 | 405 | 84 | 0 | 25 | 0 | 0 | 45 | 0 | 0 |
| Output | NZR[ ] | 100 | 405 | 84 | 25 | 45 | |||||
Code Writing
Advertisements
Solution
import java.util.Scanner;
public class FilterZeros
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int ZR[] = new int[10];
System.out.println("Enter 10 integers for array ZR:");
int nonZeroCount = 0;
for (int j = 0; j < ZR.length; j++)
{
ZR[j] = sc.nextInt();
if (ZR[j] != 0)
{
nonZeroCount++;
}
}
int NZR[] = new int[nonZeroCount];
int nzIndex = 0;
for (int j = 0; j < ZR.length; j++)
{
if (ZR[j] != 0) {
NZR[nzIndex] = ZR[j];
nzIndex++;
}
}
System.out.print("NZR[ ]\t");
for (int j = 0; j < NZR.length; j++)
{
System.out.print(NZR[j] + "\t");
}
sc.close();
}
}
shaalaa.com
Is there an error in this question or solution?
Chapter 7: Arrays - One Dimension - Exercises [Page 177]
