Write a program that uses a 3 x 3 array and randomly place each integer from 1 to 9 into the nine squares. The program

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

Write a program that uses a 3 x 3 array and randomly place each integer from 1 to 9 into the nine squares. The program

Post by answerhappygod »

Write a program that uses a 3 x 3 array and randomly placeeach integer from 1 to 9 into the nine squares. The programcalculates the magic number by adding all the numbers in the arrayand then dividing the sum by 3. The 3 x 3 array is a magicsquare if the sum of each row, each column, and each diagonal isequal to the magic number. Your program must contain at least thefollowing functions: a function to randomly fill the array with thenumbers and a function to determine if the array is a magic square.Run these functions for some large number of times, say 1,000,10,000, or 1,000,000, and see the number of times the array is amagic square.
**Finish the program using the starter code**
#include <iostream>#include <iomanip>using namespace std;
const int ROWS = 3;const int COLUMNS = 3;const int MAGIC_NUMBER = 9;
void printMatrix(int matrix[][COLUMNS], int ROWS);
bool isMagic(int matrix[][COLUMNS], int ROWS);
void fillMatrix(int matrix[][COLUMNS], int ROWS);
void initMatrix(int matrix[][COLUMNS], int ROWS); // Fillsmatrix with value -1
int main(){
// run loop here int myMatrix[ROWS][COLUMNS]; printMatrix(myMatrix, ROWS); initMatrix(myMatrix, ROWS); printMatrix(myMatrix, ROWS); return 0;}
void printMatrix(int matrix[][COLUMNS], int numOfRows){ for (int row = 0; row < numOfRows; row++) { for (int col = 0; col < COLUMNS;col++) { cout << setw(5)<< matrix[row][col] << " "; } cout << endl; }}
void initMatrix(int matrix[][COLUMNS], int ROWS){ for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLUMNS;col++) { matrix[row][col] =-1; } }}void fillMatrix(int matrix[][COLUMNS], int ROWS){ int Row_Position = 0; // Row_Position in therange 0 to 2 int Col_Position = 0; // Loop from 1 to 9 // do while loop Row_Position = rand() % 3; // Row_Position inthe range 0 to 2 Col_Position = rand() % 3; // Col_Position inthe range 0 to 2 // http://www.cplusplus.com/reference/cstdlib/rand/July 8, 2020 // if position is -1, replace with loop varible,increment loop varible // else generate new random position}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply