Ruby program to add two matrices

Ruby Example: Write a program to add two matrices.
Submitted by Nidhi, on January 23, 2022

Problem Solution:

In this program, we will create 3 matrices using the 2D array. Then we read elements of two matrices. After that, we will add both matrices and print the result.

Program/Source Code:

The source code to add two matrices is given below. The given program is compiled and executed successfully.

# Ruby program to add two matrices

Matrix1 = Array.new(2){Array.new(2)};
Matrix2 = Array.new(2){Array.new(2)};
Matrix3 = Array.new(2){Array.new(2)};

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

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


#Addition of Matrix1 and Matrix2.
i = 0;
while (i < 2)
  j = 0;
  while (j < 2) 
    Matrix3[i][j] = Matrix1[i][j] + Matrix2[i][j];
    j = j + 1;
  end
  i = i + 1;
  print "\n";
end

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

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

printf "Addition of Matrix1 and Matrix2:\n";
i = 0;
while (i < 2)
  j = 0;
  while (j < 2) 
    print Matrix3[i][j]," ";
    j = j + 1;
  end
  i = i + 1;
  print "\n";
end

Output:

Enter elements of MATRIX:
ELEMENT [0][0]: 1
Enter elements of MATRIX1:
ELEMENT [0][0]: 1
ELEMENT [0][1]: 2
ELEMENT [1][0]: 3
ELEMENT [1][1]: 4
Enter elements of MATRIX2:
ELEMENT [0][0]: 2
ELEMENT [0][1]: 3
ELEMENT [1][0]: 4
ELEMENT [1][1]: 5


MATRIX1:
1 2 
3 4 
MATRIX2:
2 3 
4 5 
Addition of Matrix1 and Matrix2:
3 5 
7 9

Explanation:

In the above program, we created 3 two-dimensional arrays Matrix1, Matrix2, Matrix3. Then we read the elements of matrices. After that, we added the Matrix1, Matrix2 and assigned the result to the Matrix3. In the end, we printed the elements of all matrices.

Ruby Arrays Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.