187k views
5 votes
Assume you are given an int variable named nPositive and a two-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire two-dimensional array that are greater than zero and assign the value to nPositive.

User Sherrard
by
4.9k points

2 Answers

4 votes

Answer:

const a2d = [[7,28, 92], [0,11,-55], [109, -25, -733]];

let nPositive = a2d.reduce((a,c) => a + c.filter(n => n>0).length, 0);

console.log(nPositive);

Step-by-step explanation:

Just for fun, I want to share the solution in javascript when using the powerful list operations. It is worthwhile learning to understand function expressions and the very common map(), reduce() and filter() primitives!

User Abr
by
5.8k points
3 votes

Answer:

public class Main

{

public static void main(String[] args) {

int nPositive = 0;

int[][] a2d = {{-7,28, 92}, {0,11,-55}, {109, -25, -733}};

for (int i = 0; i < a2d.length; i++) {

for(int j = 0; j < a2d[i].length; j++) {

if(a2d[i][j] > 0){

nPositive++;

}

}

}

System.out.println(nPositive);

}

}

Step-by-step explanation:

*The code is in Java.

Initialize the nPositive as 0

Initialize a two dimensional array called a2d

Create a nested for loop to iterate through the array. If an element is greater than 0, increment the nPositive by 1

When the loop is done, print the nPositive

User Vascowhite
by
4.9k points