Declare an array , where will contain the sum of the elements in the -th row. For each value of , calculate .
Example
Let's calculate the sums of the elements in each row of the matrix.
Algorithm implementation
Declare the arrays. Store the sum of the elements in the -th row in .
int m[101][101], sum[101];Read the input data.
scanf("%d", &n);
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &m[i][j]);For each value of , calculate the sum of the elements in the -th row and store it in .
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
sum[i] += m[i][j];Print the resulting sums.
for (i = 1; i <= n; i++)
printf("%d\n", sum[i]);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 sum[] = new int[n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
m[i][j] = con.nextInt();
sum[i] += m[i][j];
}
for (int i = 0; i < n; i++)
System.out.println(sum[i]);
con.close();
}
}Python implementation
Read the size of the array .
n = int(input())Read the input matrix.
m = [[] for _ in range(n)]
for i in range(n):
m[i] = list(map(int, input().split()))Calculate the sums of the elements in each row of the two-dimensional array.
res = [0] * n
for i in range(n):
res[i] = sum(m[i])Print the resulting sums.
for i in range(n):
print(res[i])Python implementation – on the fly
Read the size of the array .
n = int(input())Read the input matrix.
for i in range(n):Read a row of the matrix and print the sum of its elements.
lst = list(map(int, input().split()))
print(sum(lst))