Solution Review: Multiply Two Matrices
Let's go over the solution review of the challenge given in the previous lesson.
We'll cover the following...
Solution #
Press the RUN button and see the output!
Press + to interact
#include <iostream>using namespace std;// multiplication functionvoid multiplication(int arr1[][2], int row1, int col1, int arr2[][2], int row2, int col2, int result[][2]) {// Check if col of first array equal to row of second arrayif (col1 == row2) {// Traverse first array rowfor (int x = 0; x < row1; x++) {// Traverse second array columnsfor (int y = 0; y < col2; y++) {// Traverse first array columns and second array rowsfor (int z = 0; z < col1; z++) {// Multiplicationresult[x][y] = result[x][y] + arr1[x][z] * arr2[z][y];}}}}else{// Traverse first array rowfor (int x = 0; x < row1; x++) {// Traverse second array columnsfor (int y = 0; y < col2; y++) {// Fill the elements of array by -1result[x][y] = -1;}}}}// print_array functionvoid print_array(int arr[3][2], int row, int column) {// Outer loopfor (int i = 0; i < row; i++) {// Inner loopfor (int j = 0; j < column; j++) {cout << arr[i][j] << " ";}cout << endl;}}// main functionint main() {// Initialize arr1int arr1[3][2] = {{1,2},{3,4},{5,6}};// Initialize arr2int arr2[2][2] = {{10,20},{30,40}};// Initialize resultint result[3][2] = {{0,0},{0,0},{0,0}};// Call function multiplicationmultiplication(arr1,3,2,arr2,2,2,result);// Call function print_arrayprint_array(result,3,2);return 0;}
Explanation
multiplication
function
The multiplication
function takes ...