Q:

Ruby program to add two matrices

belongs to collection: Ruby Arrays Programs

0

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.

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 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 Matrix1Matrix2Matrix3. Then we read the elements of matrices. After that, we added the Matrix1Matrix2 and assigned the result to the Matrix3. In the end, we printed the elements of all matrices.

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 rows of matri... >>
<< Ruby program to calculate the sum of matrix elemen...