-
two dimensional array
I am trying to write a program that creates a magic square of two dimensions. The size of the array needs to be decided by the user so it can't be predefined. I've come across a few different ways to allocate memory for a 2 dimensional array but none without a predetermined size. Is there a way to get this to work?
Code:
int main(void)
{
int order;
double TwoDimArray[order][order];
cout <<"This program will create a magic square of an odd order\n";
cout <<"Please enter the order number you would like:\n";
cin >> order;
THANK YOU!
-
std::vector<std::vector<double> TwoDimArray(order, std::vector<double>(order));
Be sure to put it after you read in order.
-
I added that after reading 'order' and added header #include <vector> but now it is saying template argument 1 and template argument 2 are invalid errors for that line?
-
Ah, I missed a >. Updated code:
std::vector<std::vector<double>> TwoDimArray(order, std::vector<double>(order));
-
sorry but now I am recieving a conflicting declaration error for that line?
-
-
Code:
#include <iostream>
#include <vector>
using namespace std;
void MagicSquare ( double matrix, int n );
void DisplaySquare ( int matrix, int n );
int main(void)
{
int order;
double TwoDimArray[order][order];
cout <<"This program will create a magic square of an odd order\n";
cout <<"Please enter the order number you would like:\n";
cin >> order;
std::vector<std::vector<double> > TwoDimArray(order, std::vector<double>(order));
if (order%2==1)
MagicSquare( TwoDimArray, order );
else{
while (order%2==0){
cout <<"Please enter an odd number:\n";
cin >> order;
}
MagicSquare( TwoDimArray, order );
}
}
void MagicSquare ( double matrix, int n )
{
int max = n * n;
int i=0;
int j=n/2; // start position
for (int k=1; k<=max; ++k)
{
matrix[i][j] = k;
i--;
j++;
if (k%n == 0)
{
i += 2;
--j;
}
else
{
if (j==n)
j -= n;
else if (i<0)
i += n;
}
}
}
void DisplaySquare( &matrix, int n)
{
int i;
int j;
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
printf(" %3d", matrix[i][j]);
printf("\n");
}
printf("\n\n");
}
do i need to change the type of 'order'?
-
Get rid off double TwoDimArray[order][order].
Change MagicSquare to accept your new vector and get rid of the printfs (use std::cout).