# Ruby program to print the right diagonal matrix

Ruby Example: Write a program to print the right diagonal matrix.
Submitted by Nidhi, on January 25, 2022

Problem Solution:

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 print the right diagonal matrix.

Program/Source Code:

The source code to print the right diagonal matrix is given below. The given program is compiled and executed successfully.

```# Ruby program to print the
# right diagonal matrix

TwoDArr = Array.new(3){Array.new(3)}

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("Right diagonal of matrix:\n")
i = 0;
while (i < 3)
j = 0;
while (j < 3)
if ((i + j) == 2)
printf "%d ", TwoDArr[i][j];
else
printf(" ");
end
j = j + 1;
end
i = i + 1;
print "\n";
end
```

Output:

```Enter elements of MATRIX:
ELEMENT : 1
ELEMENT : 2
ELEMENT : 3
ELEMENT : 4
ELEMENT : 5
ELEMENT : 6
ELEMENT : 7
ELEMENT : 8
ELEMENT : 9
MATRIX:
1 2 3
4 5 6
7 8 9
Right diagonal of matrix:
3
5
7
```

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 printed the right diagonal of the matrix.

Preparation

What's New

Top Interview Coding Problems/Challenges!