Answer to Question #284129 in C++ for DANISH

Question #284129

Question: Implement this program by using User-defined functions.



Write a function magicCheck that takes a one-dimensional array of size 16, a two-dimensional array of four rows and four columns, and the sizes of the arrays as parameters. By adding all the elements of the one-dimensional array and dividing by 4, this function determines the magicNumber. The function then adds each row, each column, and each diagonal of the two-dimensional array and compares each sum with the magic number. If the sum of each row, each column, and each diagonal is equal to the magicNumber, the function outputs ‘‘It is a magic square’’. Otherwise, it outputs ‘‘It is not a magic number’’. Do not print the sum of each row, each column, and the diagonals.


1
Expert's answer
2022-01-02T18:17:28-0500
#include <iostream>
using namespace std;


void magicCheck(int arr1[16], int arr2[4][4], int size) {
    int s = 0;


    for (int i=0; i<16; i++) {
        s += arr1[i];
    }


    int magicNumber = s / 4;
    
    for (int row=0; row<4; row++) {
        s = 0;
        for (int col=0; col<4; col++) {
            s += arr2[row][col];
        }
        if (s != magicNumber) {
            cout << "It is not a magic number" << endl;
            return;
        }
    }


    for (int col=0; col<4; col++) {
        s = 0;
        for (int row=0; row<4; row++) {
            s += arr2[row][col];
        }
        if ( s!= magicNumber) {
            cout << "It is not a magic number" << endl;
            return;
        }
    }


    s = 0;
    for (int row=0; row<4; row++) {
        s += arr2[row][row];
    }
    if ( s!= magicNumber) {
        cout << "It is not a magic number" << endl;
        return;
    }


    s = 0;
    for (int row=0; row<4; row++) {
        s += arr2[row][3-row];
    }
    if ( s!= magicNumber) {
        cout << "It is not a magic number" << endl;
        return;
    }


    cout << "It is a magic number" << endl;
    return;
}


int main() {
    int arr1[16] = {1,2,3,4,5,6,7,8,9,
                    10,11,12,13,14,15,16};
    int arr2[4][4] = {{16, 2, 3, 13},
                      {5, 11, 10, 8},
                      {9, 7, 6, 12},
                      {4, 14,15,1}};
    
    magicCheck(arr1, arr2, 4);


    cout << endl;
    arr2[0][0] = 7;
    arr2[2][1] = 16;
    magicCheck(arr1, arr2, 4);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog