Java bootcamp · Lab 46

Matrix sum

medium2D Arrays12 minLesson: 2D Arrays

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read r c, then r lines of c ints. Print the sum of all elements.

Examples

Example 1
Input
2 3
1 2 3
4 5 6
Output
21
Hint
  1. Nested loops accumulate.
Show correct code

Peek only after you have tried. You can still Check your own version.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int r = in.nextInt(), c = in.nextInt();
    long sum = 0;
    for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) sum += in.nextInt();
    System.out.println(sum);
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.