1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
#include <iostream>
using namespace std;
//return true if rows and columns sum to the same value
bool sum_square (int* TDarray[], int rows, int columns);
int main(){
int ** userArray;
int userRows; // user selects number of rows they would like
int userColumns; // and the number of rows
cout << "Please enter number of rows of your square." << endl;
cin >> userRows;
cout << "Please enter the number of columns. (Same for as first fora square)." << endl;
cin >> userColumns;
userArray = new int*[userRows];
for (int i = 0; i < userRows; i++)
userArray[i] = new int [userColumns];
cout << "Please fill out your array by entering integers." << endl;
cout << "You will fill out your array left to right, and then" << endl;
cout << "go down the rows." << endl;
for (int i = 0; i < userRows; i++) //loop through rows
{
for (int j = 0; j < userColumns; j++) // loop through columns
{
cin >> userArray[i][j];
}
}
cout << "Your entered array is " << endl;
for (int a = 0; a < userRows; ++a)
{
for (int b = 0; b < userColumns; ++b)
{
cout << userArray[a][b] << (b == userColumns-1 ? "":" ");
}
cout << '/n';
}
//
if (sum_square(userArray, userRows, userColumns) == true)
{
cout << "And the rows, columns, and diagonals sum to the same value." << endl;
}
else
{
cout << "And at least on of the rows, columns, or diagonals" << endl;
cout << "do not sum to the same value." << endl;
}
for (int i = 0; i < userRows; i++)
delete []userArray[i];
delete []userArray;
return 0;
}
bool sum_square (int* TDarray[], int rows, int columns)
{
int totalInRow, totalInColumn; // holds sums of the rows & columns
int totalDiag1, totalDiag2; //holds sums of the diagonals
for (int i = 0; i < rows; i++) //sum the top-down left to right diagonal
totalDiag1 += TDarray[i][i];
for (int i = rows; i >= 0; i--) //sum the top down right to left diagonal
totalDiag2 += TDarray[rows - i][i - 1];
if (totalDiag1 != totalDiag2) //if diags don't sum to same value
return false;
for (int i = 0; i < rows; i ++) //sum the rows
{
totalInRow = 0;
for (int j = 0; j < columns; j++)
{
totalInRow += TDarray[i][j];
}
if(totalInRow != totalDiag1) //if rows don't equal diagonals, return false
return false;
}
for (int i = 0; i < columns; i++)
{
totalInColumn = 0;
for (int j = 0; j < rows; j++)
{
totalInColumn += TDarray[j][i];
}
if (totalInColumn != totalDiag1) //if columns don't sum to diagonals
return false;
}
return true;
}
|