Creating An Array Containing The Sum Of Each Row Elements

In this article, we will create an Array containing the sum of each row elements in a 2D Array

As you have now understood the concept, first try to solve the problem by yourself before you look into the below solution.

Understanding the Problem

Given a 2D array, our objective is to calculate the sum of elements in each row and store these sums in a separate 1D array. Each element of the new array will represent the sum of elements in the corresponding row of the 2D array.


Approach

To create an array containing the sum of each row elements in a 2D array, we'll follow these steps:


Step-by-Step Solution

Step 1: Initialize the Result Array

We'll start by creating a new 1D array to store the sums of each row elements. The size of this array will be equal to the number of rows in the 2D array.

Step 2: Calculate Row Sums

Next, we'll iterate through each row of the 2D array and calculate the sum of elements in each row using a loop.

Step 3: Print the Result

After calculating the sum of elements in each row and storing them in the new array, we'll print the contents of the new array.

Code Implementation

Here's the complete code implementing the above approach:

Exercise

Write a program to Create an ArrayList containing sum of each row elements and print it.