Q:

Ruby program to calculate the sum of left diagonal the matrix

belongs to collection: Ruby Arrays Programs

0

In this program, we will create a matrix using the 2D array. Then we read elements of the matrix from the user. After that, we will calculate the sum of the left diagonal matrix and print the result.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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

# Ruby program to calculate the sum of 
# left diagonal the matrix

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

printf "Enter elements of MATRIX:\n";
i = 0;
while (i < 3) 
  j = 0;
  while (j < 3) 
    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 < 3)
  j = 0;
  while (j < 3) 
    print TwoDArr[i][j]," ";
    j = j + 1;
  end
  i = i + 1;
  print "\n";
end

printf("Left diagonal of matrix:\n")
i = 0;
while (i < 3) 
    j = 0;
    while (j < 3) 
        if (i == j)
            sum = sum + TwoDArr[i][j];
            printf "%d ", TwoDArr[i][j];
        else
            printf(" ");
        end
        j = j + 1;
    end
    i = i + 1;
    print "\n";
end

printf "Sum of left diagonal of matrix: %d\n",sum;

Output:

Enter elements of MATRIX:
ELEMENT [0][0]: 1
ELEMENT [0][1]: 2
ELEMENT [0][2]: 3
ELEMENT [1][0]: 4
ELEMENT [1][1]: 5
ELEMENT [1][2]: 6
ELEMENT [2][0]: 7
ELEMENT [2][1]: 8
ELEMENT [2][2]: 9
MATRIX:
1 2 3 
4 5 6 
7 8 9 
Left diagonal of matrix:
1   
 5  
  9 
Sum of left diagonal of matrix: 15

Explanation:

In the above program, we created a 3X3 matrix TwoDArr using the 2D array. Then we read the elements of the matrix. After that, we calculated the sum of left diagonal elements and printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to calculate the sum of right diagona... >>
<< Ruby program to print the right diagonal matrix...