Question: C++. Please fix this code. The code does not use matrices with fixed size at compile time. The code uses a matrix set to n

C++. Please fix this code. The code does not use matrices with fixed size at compile time. The code uses a matrix set to n x n, which is not static. Edit the code such that the matrices are fixed at compile time and are static. There should be no changes to the output of this original code and your modified code (for example, when you enter '5' in the original code, you should receive the same result when you enter '5' in your modified code).

/*description: A 7x7 static matrix is created and used to produce an nxn magic matrix.

In a magic matrix, numbers appear only once and sum of the columns, rows, and diagonals are equal.

The user is queried for an odd integer n, where n can be 3, 5, or 7.*/

#include

#include

using namespace std;

//the following function generates a magic matrix and prints it @param n

void generateMagicMatrix(int n) { //this is the declaration of the magic matrix int matrix[n][n]; //must initialize each element of the matrix to 0 for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { matrix[row][col] = 0; } }

//the first element will be placed at cartesian coordinates: [n/2, n-1] int row = n / 2; int col = n - 1; //we must assign elements to the matrix one at a time for (int number = 1; number <= n * n;) { //3rd condition if (row == -1 && col == n) { row = 0; col = n - 2; } else { //now to wrap around the index if (col == n) col = 0; if (row < 0) row = n - 1; } //2nd condition if (matrix[row][col]) { //the position [row, col] already contains a number col -= 2; row++; continue; } else { matrix[row][col] = number; number++; //incremented col++; row--; //1st condition } } //to display the final matrix cout << "Done! The magic matrix of " << n << " X " << n << " Matrix => " << endl; for (row = n-1; row >= 0; row--) { for (col = n-1; col >= 0; col--) cout << setw(5) << matrix[col][row] << " "; cout << endl; } }

//query the user int main() {

int g; do { cout << "Please enter the odd integer 3, 5, or 7: "; cin >> g; } while (g % 2 != 1); generateMagicMatrix(g); return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!