Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Hello Can anyone help me fix my code please? This is what I need to fix. Using constexpr to set the values of ROWS and

Hello Can anyone help me fix my code please? This is what I need to fix.

Using constexpr to set the values of ROWS and COLS and then using those values to allocate the matrix is causing runtime allocation. I was curious and actually checked and displayed the address of the matrix using your code, and it is clearly being allocated from the heap. These values MUST be fixed at compile time.

Please show that you have fixed it by displaying the address of the matrix.

#include

// I am using only what I need

// from namespace std;

using std::cin;

using std::cout;

using std::endl;

// Size of the matrix at compile-time.

constexpr int ROWS = 4;

constexpr int COLS = 4;

// display the contents of the matrix.

void displayMatrixContents(int matrix[][COLS])

{

cout << "Col\t1\t2\t3\t4 ";

cout << "------------------------------------ ";

for (int rows = 0; rows < ROWS; rows++)

{

cout << "Row: " << rows + 1;

for (int cols = 0; cols < COLS; cols++)

{

cout << "\t" << matrix[rows][cols];

}

cout << endl;

}

}

bool searchNumberInMatrix(int matrix[][COLS], int &row, int &col, int number)

{

bool Found = false;

for (int rows = 0; rows < ROWS && !Found; rows++)

{

for (int cols = 0; cols < COLS && !Found; cols++)

{

if (matrix[rows][cols] == number)

{

// Once it is found, set the flag to true

// so the for loop will stop. No reason to

// keep looping.

Found = true;

row = rows + 1;

col = cols + 1;

}

}

}

return Found;

}

int main()

{

static int matrix[ROWS][COLS] = { { 18, 39, 91, 91 },

{ 67, 3, 9, 95},

{ 69, 3, 68, 93},

{ 69, 21, 92, 92} };

displayMatrixContents(matrix);

cout << " Enter an integer: ";

int number{};

cin >> number;

// Declare these 2 variables to be used if the number is found

int row{};

int col{};

if (searchNumberInMatrix(matrix, row, col, number))

{

cout << " Found " << number << " at "

<< "Row # " << row << " Col # "

<< col << endl;

}

else

{

cout << " Number " << number << " was not found" << endl;

}

return 0;

}

Like

Comment

Share

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Financial management theory and practice

Authors: Eugene F. Brigham and Michael C. Ehrhardt

12th Edition

978-0030243998, 30243998, 324422695, 978-0324422696

Students also viewed these Programming questions