Advertisements
Advertisements
प्रश्न
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 | |||||
कोड लेखन
Advertisements
उत्तर
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
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 7: Arrays - One Dimension - Exercises [पृष्ठ १७७]
