magic square problem

This is a discussion on magic square problem within the C++ Programming forums, part of the General Programming Boards category; I wanna solve magic square program written in c++. I have everything working except the elements in first column are ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    2

    magic square problem

    I wanna solve magic square program written in c++. I have everything working except the elements in first column are misplaced.
    It should look like
    6 1 8
    7 5 3
    2 9 4

    But mine is resulting
    2 1 8
    6 5 3
    7 9 4

    My code goes like this:

    [code]
    #include<iostream>
    #include<cmath>

    using namespace std;

    int main()
    {
    int size=3;

    int magic[3][3];
    int row,col;

    row=0;
    col=size/2;


    for(int i=1;i<=size*size;i++)
    {
    magic[row][col]=i;

    row--;
    col--;

    if(i%size ==0)
    {
    row+=2;
    col++;
    }
    else
    {
    if(col==0)
    {
    col=col+size;
    }
    else if(row<0)
    {
    row=row+size;
    }
    }

    }

    for(row=0;row<size;row++)
    {
    for(col=0;col<size;col++)
    {
    cout<<magic[row][col]<<" ";
    if((col+1)%3==0)
    cout<<endl;
    }
    }

    return (0);
    }
    [/code]
    Anybody who has specific idea will be greatly appreciated.
    Thanks
    ranjan

  2. #2
    Registered User
    Join Date
    Apr 2009
    Posts
    2
    anyway i already solved it...thank god! The change was made as shown:
    Code:
       else
    		 {
    			 if(col<0)
    			 {
    				 col=col+size;
    			 }
    			 else if(row<0)
    			 {
    				 row=row+size;
    			 }
    		 }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Square Root Problem
    By punter in forum C++ Programming
    Replies: 8
    Last Post: 10-20-2006, 02:46 PM
  2. help on magic square
    By katway in forum C Programming
    Replies: 2
    Last Post: 03-07-2005, 05:44 PM
  3. help with magic square
    By dragon_heart in forum C++ Programming
    Replies: 3
    Last Post: 11-26-2004, 04:56 PM
  4. for loops using square roots, square, Cube
    By lotf in forum C Programming
    Replies: 3
    Last Post: 03-21-2004, 03:29 AM
  5. Characters in a Magic Square Program
    By TeamGreen in forum C++ Programming
    Replies: 1
    Last Post: 03-16-2004, 07:08 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21