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.
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.