Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the position of an object in a 2D array in C++?

For an assignment I have to make an 8×8 grid, randomly place two or more Js in it, then run through it and say where each J is. I’ve gotten most of it, but whenever I try to output the positions, it outputs garbage instead.

This is what I have right now:

#include <iostream>
using namespace std;

int main()
{
    char array[8][8] = {
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
        {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
    };
    srand(time(NULL));

    for (int i = 0; i < 2; i++) {
        array[rand() % 5][rand() % 5] = 'J';
    }


    //print the grid
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            cout << "\t" << array[i][j];
        }
        cout << endl;
    }

    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            if (array[i][j] == 'J')
            {
                cout << "Jewel found at " << array[i] << ", " << array[j] << endl;
            }
        }
        cout << endl;
    }
}

I know it’s probably because it’s outputting the entire row/column it’s at, but I’m kind of stupid and can’t think of how to make it do what i want.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was hoping it would just output the coordinates but i got some other stuff instead

>Solution :

Your cout statement that is printing a found position is wrong. It should be printing the values of i and j themselves, but instead you are printing the memory addresses of the array elements which are held at indexes i and j.

IOW, change this:

cout << "Jewel found at " << array[i] << ", " << array[j] << endl;

To this instead:

cout << "Jewel found at " << i << ", " << j << endl;

Also, your rand() expressions should be using % 8 instead of % 5.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading