Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN c++ enhance understanding in pointer and arrays(2d arrays specifically). Use

ID: 3848831 • Letter: I

Question

IN c++ enhance understanding in pointer and arrays(2d arrays specifically). Use c++ to write a program that will use functions for the following points.

1.Reading input

You will be given two numbers from command line, e.g., m and n, where m is matrix row and n is matrix column.

use: int main(int argc, char*argv[])

2.Memory allocation

After validation for m and n (positive numbers!), define two matrices M (m × n) and N (m × n). These two matrices could be initialized with double-dimensional array in C++, e.g., double **matrixM, **matrixN, by means of new in C++.

3.Matrix initialization

Initialize matrix elements with random double number in C++. Elements in matrixM (the first matrix) should be a random double in range [-m,m], while elements in matrixN (the second matrix) in range [-n,n]. Might see randomization here.

4.Matrix addition

Create a third matrixC from the addition of matrixA and matrixB.

5.Element print

Print the smallest and largest element in matrixC by traversing on and comparing all elements.

6.Memory Release

Release memory for all three matrices by using delete.

Explanation / Answer

#include <iostream>

#include <cstdlib>

using namespace std;

int main(int argc, char *argv[]) {

srand(time(0));

    if(argc <!=3){

cout<<"Please run the program correctly, we need both m,n value";

}

int m = atoi(argv[1]);//atoi is used to convert string to integer

int n = atoi(argv[2]);

double ** matrixM;

double ** matrixN;

double ** matrixC;

int i,j;

matrixM = new double*[m];

matrixN = new double*[m];

matrixC = new double*[m];

for(i=0;i<m;i++){

matrixM[i] = new double*[n];

matrixN[i] = new double*[n];

matrixC[i] = new double*[n];

}

//initialize with random values

for(i=0;i<m;i++){

for(j=0;j<n;j++){

matrixM[i][j] = ((double)rand() / m)*2m -m; // to generate random between -m,m

matrixN[i][j] = ((double)rand() / n)*2n -n;

}

}

//Addition

for(i=0;i<m;i++){

for(j=0;j<n;j++){

matrixC[i][j] =matrixM[i][j] +matrixN[i][j];

}

}

//Find Min and Max

double min = matrixC[0][0];

double max = matrixC[0][0];

for(i=0;i<m;i++){

for(j=0;j<n;j++){

if(min>matrixC[i][j])

min = matrixC[i][j];

else if(max<matrixC[i][j])

max = matrixC[i][j];

}

}

cout<<"Min is :"<<min<<endl;

cout<<"Max is :"<<max<<endl;

//deletion

for(i=0;i<m;i++){

delete [] matrixM[i];

delete [] matrixN[i];

delete [] matrixC[i];

}

delete [] matrixM;

delete [] matrixN;

delete [] matrixC;

}