Thread: Magic Squares!

  1. #1
    Registered User
    Join Date
    Apr 2004

    Magic Squares!

    Ive got this homework to do concerning magic squares. Could anyone help me out on the C++ code for this problem?

    An n by n matrix that is filled with the numbers 1, 2, 3, ... n*n is a Magic Square if the sum of the elements in each row, in each column and in the two diagonals is the same value. For example

    16 3 2 13
    5 10 11 8
    9 6 7 12
    4 15 14 1

    is a Magic Square. Write a program that reads n from the user and then prompts for n*n values, ensuring that each is between 1 and n*n.
    :Check that each number occurs only once
    :Check if the sums of the rows, columns and diagonals are equal
    isplay the square on the screen
    Based on these facts, inform the user whether the numbers form a Magic Square or not.
    You must use 2-Dimensional static arrays! Use a 4x4 array.

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003

    Step one. Write an empty program that does nothing but compile.
    Step two. Create a 2-dimensional static array that is 4x4. Make sure it compiles.
    Step three. Put code in to output the values in the square. Compile it and run it. Hard code your own values (like the example above) to test that this works. You can remove that later.
    Step four. Add code to prompt the user for the n*n values. Put this code before the code you did in Step three. Remove the hardcoded values you used to test Step three. Compile it and run it. The values you input should then be printed back out in the form of a square.
    Step five. Add the validation that ensures that each number is between 1 and n*n. Compile it, run it and test it.
    Step six. Figure out how to test that every number appears only once. Decide what to do if this rule is violated (your assignment doesn't specify). Code it, compile it, run it, test it, until it works.
    Step seven. Add code to validate whether the square is magic or not. Compile it, run it, test it, until it works.
    Step eight. Smile, you are done.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Generating an image of squares?
    By vopo in forum C# Programming
    Replies: 3
    Last Post: 10-21-2008, 10:15 AM
  2. Help an ambitious 16 year old learn C
    By Xlayer in forum C Programming
    Replies: 20
    Last Post: 10-08-2007, 04:15 PM
  3. Forced moves trouble!!
    By Zishaan in forum Game Programming
    Replies: 0
    Last Post: 03-27-2007, 06:57 PM
  4. help on magic square
    By katway in forum C Programming
    Replies: 2
    Last Post: 03-07-2005, 05:44 PM
  5. Magic Squares
    By KidCourageous in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2004, 12:26 AM