# Ruby program to calculate the sum of matrix elements

Ruby Example: Write a program to calculate the sum of matrix elements.
Submitted by Nidhi, on January 23, 2022

Problem Solution:

In this program, we will create a two-dimensional array. Then we read the matrix from the user and calculate the sum of matrix elements.

Program/Source Code:

The source code to calculate the sum of matrix elements is given below. The given program is compiled and executed successfully.

```# Ruby program to calculate the sum
# of matrix elements

TwoDArr = Array.new(2){Array.new(2)}
sum = 0;

printf "Enter elements of MATRIX:\n";
i = 0;
while (i < 2)
j = 0;
while (j < 2)
printf "ELEMENT [%d][%d]: ", i, j;
TwoDArr[i][j] =  gets.chomp.to_i;
j = j + 1;
end
i = i + 1;
end

printf "MATRIX:\n";
i = 0;
while (i < 2)
j = 0;
while (j < 2)
sum = sum +TwoDArr[i][j];
print TwoDArr[i][j]," ";
j = j + 1;
end
i = i + 1;
print "\n";
end

printf "Sum of matrix elements: %d\n",sum;
```

Output:

```Enter elements of MATRIX:
ELEMENT : 1
ELEMENT : 2
ELEMENT : 3
ELEMENT : 4
MATRIX:
1 2
3 4
Sum of matrix elements: 10
```

Explanation:

In the above program, we created a two-dimensional array TwoDArr. Then we read the elements of the 2D array. After that, we calculated the sum of matrix elements and printed the result.

Preparation

What's New

Top Interview Coding Problems/Challenges!