Sum of positives in a matrix#8524

Sum of positives in a matrix (Editorial)

Using a double loop, compute the sum of the positive elements in the matrix (two-dimensional array).

Algorithm implementation

Declarw a two-dimensional array .

int m[101][101];

Read the input data. In the variable , compute the sum of all its positive elements.

scanf("%d",&n);
s = 0;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
{
  scanf("%d",&m[i][j]);
  if (m[i][j] > 0) s = s + m[i][j];
}

Print the answer.

printf("%d\n",s);

Java implementation

import java.util.*;

public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int m[][] = new int[n][n];
    
    int s = 0;
    for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
    {
      m[i][j] = con.nextInt();
      if (m[i][j] > 0) s = s + m[i][j];
    }

    System.out.println(s);
    con.close();
  }
}

Python implementation

Read the input data.

n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]

In the variable , compute the sum of all the positive elements in the matrix.

sum = 0
for i in range(n):
  for j in range(n):
    if a[i][j] > 0: sum += a[i][j]

Print the answer.

print(sum)

Python implementation — list comprehension

Read the input data.

n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]

Compute the sum of all the positive elements in the matrix.

sum = sum(a[i][j] for i in range(n) for j in range(n) if a[i][j] > 0)

Print the answer.

print(sum)