C++ bootcamp · Lab 36

Matrix sum

medium2D Arrays12 minLesson: 2D Arrays

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

QuestionHint and solution stay closed until you open them

Read two integers r and c, then r × c integers in row-major order.

Print the sum of every entry.

Input. r c, then r*c integers.

Output. One integer: the total.

Constraints

  • 1 ≤ r, c ≤ 20

Examples

Example 1
Input
2 3
1 2 3 4 5 6
Output
21
Hint
  1. Nested loops over i and j; add each value you read.
Show correct code

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

#include <iostream>

int main() {
  int r, c;
  std::cin >> r >> c;
  long long sum = 0;
  for (int i = 0; i < r; i++) {
    for (int j = 0; j < c; j++) {
      int x;
      std::cin >> x;
      sum += x;
    }
  }
  std::cout << sum << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.