Matrix multiplication / Huawei machine test (C/C + +)

Two dimensional array allocation and release

Title Description

  • If A is A matrix of x rows and y columns, and B is A matrix of y rows and z columns, multiply A and B, and the result will be another matrix C of x rows and z columns. Each element of this matrix is determined by the following formula:

Archetype:

voidmatrix_multiply(int *m1,int *m2,int *r, int x, int y, int z);

Input parameters:

Matrix of * m1: X row and Y column (array1[x][y])

int * m2: matrix of row y and column z (array2[y][z])

int x: number of rows of matrix m1

int y: number of columns in matrix m1 / number of rows in matrix m2

int z: number of columns of matrix m2

Output parameters:

int * r: the result of matrix m1 and m2 multiplication (array3[x][z])

 

Return value:

        void

 

Enter a description:

Enter Description:
1. Number of rows of the first matrix
2. The number of columns of the first matrix and the number of rows of the second matrix
3. Number of columns of the second matrix
4. Value of the first matrix
5. Value of the second matrix

Output Description:

Output the result of multiplication of two matrices

Example 1

input

2
2
2
3 8
8 0
9 0
18 9

output

171 72
72 0

Code:

//Matrix multiplication
#include<iostream>
using std::cin;
using std::cout;
int main()
{
	int first_row, fcol_srow, second_col;
	while (cin >> first_row >> fcol_srow >> second_col)
	{
		int** first, **second, **result;
		first = new int*[first_row];//alloc room for first mat
		for (int i = 0; i < first_row; i++)
			first[i] = new int[fcol_srow];
		second = new int*[fcol_srow];//alloc room for second mat
		for (int i = 0; i < fcol_srow; i++)
			second[i] = new int[second_col];
		result = new int*[first_row];//alloc room for result mat
		for (int i = 0; i < first_row; i++)
			result[i] = new int[second_col];
		for (int i = 0; i < first_row; i++)//input data for first mat
			for (int j = 0; j < fcol_srow; j++)
				cin >> first[i][j];
		for (int i = 0; i < fcol_srow; i++)//input data for second mat
			for (int j = 0; j < second_col; j++)
				cin >> second[i][j];
		for (int i = 0; i < first_row; i++)//calculate data for result mat
		{
			for (int j = 0; j < second_col; j++)
			{
				int sum = 0;
				for (int k = 0; k < fcol_srow; k++)
					sum += first[i][k] * second[k][j];
				result[i][j] = sum;
			}
		}
		for (int i = 0; i < first_row; i++)
		{
			for (int j = 0; j < second_col; j++)
				cout << result[i][j] << " ";
			cout << std::endl;
		}
		for (int i = 0; i < first_row; i++)
		{
			delete[] first[i];
			first[i] = NULL;
		}
		delete[] first;
		first = NULL;
		for (int i = 0; i < first_row; i++)
		{
			delete[] result[i];
			result[i] = NULL;
		}
		delete[] result;
		result = NULL;
		for (int i = 0; i < fcol_srow; i++)
		{
			delete[] second[i];
			second[i] = NULL;
		}
		delete[] second;
		second = NULL;
	}
	return 0;
}

 

Posted by fI_Ux on Tue, 17 Dec 2019 07:41:07 -0800