Given nA and a[0], a[1], ..., a[nA - 1], give a segment of code that will copy t
ID: 3930832 • Letter: G
Question
Given nA and a[0], a[1], ..., a[nA - 1], give a segment of code that will copy the non-zero elements of array "a" into an array "b", "squeezing out the zeroes", and setting nB equal to the number of non-zero elements in b. That is, if nA=13 and the contents of a[i], where i = 0 to nA - 1 are initially 0.0, 1.2, 0.0, 0.0, 0.0, 2.3, 0.0, 9.7, 5.6, 0.0, 3.6, 0.0, 0.0 then after execution of the code the contents should be nB=5, b[0]=1.2, b[1]=2.3, b[2]=9.7, b[3]=5.6, and b[4]=3.6. Note: You may assume both arrays are of type double.
Explanation / Answer
NonZeroArray.java
import java.util.Arrays;
public class NonZeroArray {
public static void main(String[] args) {
double a[] = {0.0, 1.2, 0.0, 0.0, 0.0, 2.3, 0.0, 9.7, 5.6, 0.0, 3.6, 0.0, 0.0 };
int nonZeroCount = 0;
for(int i=0; i<a.length; i++){
if(a[i] != 0){
nonZeroCount++;
}
}
double b[] = new double[nonZeroCount];
for(int i=0,j=0; i<a.length; i++){
if(a[i] != 0){
b[j++] = a[i];
}
}
System.out.println("First Array elements: "+Arrays.toString(a));
System.out.println("Second Array elements: "+Arrays.toString(b));
}
}
Output:
First Array elements: [0.0, 1.2, 0.0, 0.0, 0.0, 2.3, 0.0, 9.7, 5.6, 0.0, 3.6, 0.0, 0.0]
Second Array elements: [1.2, 2.3, 9.7, 5.6, 3.6]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.