6

For those unfamiliar with the classic magic square algorithm: A magic square is a two dimensional array (n x n) which contains a numerical value between the values 1 and n^2 in each location. Each value may appear only once. Furthermore, the sum of each row, column and diagonal must be the same. The input should be odd as I am writing an odd magic square solution.


I have completed the problem but as of now it has an unknown bug (logic? output?) that has been vexing me for the past hour. The values that are output are very off mark. Any help would be very much appreciated:


#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
  int n;

  cout<< "Please enter an odd integer: ";
  cin>>n;

  int MagicSquare[n][n];


  int newRow,
  newCol;

  // Set the indices for the middle of the bottom i
  int i =0 ;
  int j= n / 2;

  // Fill each element of the array using the magic array
  for ( int value = 1; value <= n*n; value++ )
  {
     MagicSquare[i][j] = value;
     // Find the next cell, wrapping around if necessary.
     newRow = (i + 1) % n;
     newCol = (j + 1) % n;
     // If the cell is empty, remember those indices for the
     // next assignment.
     if ( MagicSquare[newRow][newCol] == 0 )
     {
        i = newRow;
        j = newCol;
     }
     else
     {
        // The cell was full. Use the cell above the previous one.
        i = (i - 1 + n) % n;
     }

  }


  for(int x=0; x<n; x++)
  {
     for(int y=0; y<n; y++)
         cout << MagicSquare[x][y]<<" ";
     cout << endl;
  }
}
false
  • 10,264
  • 13
  • 101
  • 209
user533053
  • 79
  • 1
  • 1
  • 3
  • 4
    And the bug is _what_, exactly? What's it doing, and what's the difference between that and what it **should** be doing? Have you tried using a debugger? – Matt Ball Dec 07 '10 at 01:19
  • Have you attempted to debug it in a debugger. GDB and VS C++ Express are free. Not many excuses not to. – linuxuser27 Dec 07 '10 at 01:21
  • initialize the array with initial value i.e. 0. or use a language which initialize array to default value. Like java initialize int to 0, float to 0.0 and object array to null. – Trying Aug 27 '13 at 14:11
  • 1
    This was literally the very first problem I ever coded. Thanks for the memory! – Floris Apr 25 '14 at 23:07
  • you have bug, diagonals is not the same – bumbeishvili Nov 23 '16 at 11:38

5 Answers5

12

You forgot to initialize your MagicSquare to contain all zeros:

  for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
      MagicSquare[i][j] = 0;
    }
  }

Thus this check will almost always fail:

if ( MagicSquare[newRow][newCol] == 0 ) {
   i = newRow;
   j = newCol;
}

As C/++ doesn't initialize them to 0 for you.

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
2
#include<iostream.h>
#include<iomanip.h>
int main()
{
     int arr[25][25]={0};
     cout<<"Enter size(odd):";
     int size;
     cin>>size;
     int i=0,j=(size-1)/2,n=1;
     arr[i][j]=n;
     while(n<=size*size){
           i--;
           j--;
           if(i<0&&j>=0){
                i=size-1;
                arr[i][j]=n;
                n++;
          }else if(j<0&&i>=0){
                j=size-1;
                arr[i][j]=n;
                n++;
          }else if(i<0&&j<0){
                i=i+2;
                j=j+1;
                arr[i][j]=n;
                n++;
          }else if(arr[i][j]!=0){
                i=i+2;
                j=j+1;
                arr[i][j]=n;
                n++;
          }else{  
                arr[i][j]=n;
                n++;
          }
      }
      for(i=0,i<ize;i++){  
            for(j=0,j<size;j++){
                  cout<<setw(3)<<arr[i][j];
            }
            cout<<endl;
      }
      return 0;
  }
  • 2
    Code-only answers are not encouraged. Please, add explanations about _why_ and _how_ you code works. – lolbas Feb 27 '18 at 13:13
0

you cant take the number n from the user ,because you have to define the size of the array with constant

Haitham Khedr
  • 99
  • 2
  • 10
  • That in not true. You can define an array of arbitrary size by putting it in a separate scope { ... }. Of course, watch your stack in this case. – Archie Jun 16 '13 at 20:17
  • @Archie Could you elaborate please on why this is legal syntax? I didn't follow, but everybody else seems to be on the same page with you. – Panzercrisis Aug 27 '13 at 15:18
  • @Archie: That is not correct. C++ does not allow variable length arrays, whatever scope they are in. Some compilers may allow it as an extension, but it's not standard. – zindorsky Aug 27 '13 at 16:08
0

You should create the dynamic array in order to listen dimension from keyboard, but don't forget to delete arrays when you don't need it

0

you must initialize contain all elements to zeros:

  memset(MagicSquare, 0, sizeof(MagicSquare));

Othewise it show garbage value.
N.B: memset function include in cstring header file.

Your corrected code:

#include<iostream>
#include<iomanip>
#include <cstring>
using namespace std;

int main()
{
  int n;

// cout<< "Please enter an odd integer: ";
  cin>>n;

  int MagicSquare[n][n];


  int newRow,
  newCol;
   memset(MagicSquare, 0, sizeof(MagicSquare));
  // Set the indices for the middle of the bottom i
  int i =0 ;
  int j= n / 2;

  // Fill each element of the array using the magic array
  for ( int value = 1; value <= n*n; value++ )
  {
     MagicSquare[i][j] = value;
     // Find the next cell, wrapping around if necessary.
     newRow = (i + 1) % n;
     newCol = (j + 1) % n;
     // If the cell is empty, remember those indices for the
     // next assignment.
     if ( MagicSquare[newRow][newCol] == 0 )
     {
        i = newRow;
        j = newCol;
     }
     else
     {
        // The cell was full. Use the cell above the previous one.
        i = (i - 1 + n) % n;
     }

  }


  for(int x=0; x<n; x++)
  {
     for(int y=0; y<n; y++)
         cout << MagicSquare[x][y]<<" ";
     cout << endl;
  }
}
e-sushi
  • 13,786
  • 10
  • 38
  • 57
rashedcs
  • 3,588
  • 2
  • 39
  • 40