Thread: using 2-d arrays

  1. #1
    newbie40
    Guest

    using 2-d arrays

    hi, im creating a game that solves an 8 puzzle
    i need to take in 9 numbers, 0-9 and i need it to be a 3X3 matrix because the "board" uses a 2-d array. how do i cin those numbers??



    int main () {

    int maxNum;

    cout << "Welcome to the Eight-Puzzle Solver." << "\n"

    << "What is the upper limit on the number of"
    << " nodes I should search?" << endl;

    cin >> maxNum;

    cout << "\n" << "\n"
    << "Please input 9 digits (0--8) to" << "\n"
    << "specify the initial board position:";

    cin >> ????

    }

  2. #2
    elad
    Guest
    doing a search of the board will provide you with a number of similar responses.

    also 0 - 9 is ten numbers, not nine.

    Basically you use double index operators to access each spot.

    int 2D[3][3];
    for(i = 0; i < 3; i++)
    {
    for(x = 0; x < 3; x++)
    {
    2D[i][x] = (3 * i) + x;
    }
    }

  3. #3
    newbie40
    Guest
    oops, i mean 0-8, sorry

    so do i just

    cin >> num1 >> num2 >> num3 >> num4 >> num5 >> num6 >> num7 >> num8 >> num9;

    and then assign these numbers to a 2d array?

    thanks for the help.

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    An example:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main(void)
    {
        int board[3][3] = {{0,0}};
        
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
            {
                cout <<"Enter Row " <<i <<" Col " <<j <<" :";
                cin >> board[i][j];
            }
            
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                cout <<"Row " <<i <<" Col " <<j <<" :" <<board[i][j] <<endl;
        
        return 0;
        
    }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    elad
    Guest
    If you want user input for the various spots use Hammer's code. If you want to assign the values 0-8 to the respective spots, use mine. Note how both use a name[][] format to indicate where a specific piece of data is to be stored.

  6. #6
    newbie40
    Guest

    Smile

    thank you very much

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function to read in two arrays
    By ssmokincamaro in forum C Programming
    Replies: 7
    Last Post: 11-12-2008, 07:59 AM
  2. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 04:24 PM
  3. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  4. Need Help With 3 Parallel Arrays Selction Sort
    By slickwilly440 in forum C++ Programming
    Replies: 4
    Last Post: 11-19-2005, 10:47 PM
  5. Crazy memory problem with arrays
    By fusikon in forum C++ Programming
    Replies: 9
    Last Post: 01-15-2003, 09:24 PM