Arrays
I'm trying to make a program that uses an array to track a boat's position. Kind of like battleship but not quite that in depth. I want to have a grid of 5x5 and have spaces everywhere except where the boat is located and when the user enters a letter for which direction to move the boat it will print out the boat's new position. This is what I have so far:
#include <iostream>
using namespace std;
const int ROWS = 5;
const int COLUMNS = 5;
void Map( double[ROWS][COLUMNS] ); //declaration
int main()
{
int Map[5][5];
char direction;
cout >> "Enter a letter to move Up, Down, Left, or Right or E to Exit: ";
cin >> direction;
Map[r][c];
int x;
cin >> x;
}
//------------------------------
// plot a 5 by 5 grid with B at position r, c
void plot(int r, int c)
{
for(int i=0; i<5; i++)
{
cout<< "\n " << i;
for(int j=0; j<5; j++)
if(i == r && j == c) cout << " B"; else cout << " -";
}
}
[1127 byte] By [
krazykrisi] at [2007-11-11 10:12:06]

# 1 Re: Arrays
It's a double array really.
You have 5 rows and 5 columns. This means that you have 5*5=25 values.
So Map[0][0] = 1; and Map[4][4] = 25; If the boat is at position 12 then the corresponding array member would be 2 * 10 + 2 which means the third row and the second column Map[2][1]. Now if the user presses Up the value will be 12 - 5 (Map[1][1]=7), Down will be 12 + 5 (Map[3][1]=17) and Left will be 12 - 1 (Map[2][0]=11), Right will be 12 + 1 (Map[2][2]=13).
The algorithm for the boat's position array member is as follows:
Map[BoatPos - 5 * (BoatPos/5)][BoatPos%5 - 1] = BoatPos;
except when the boat is in the first row:
Map[0][BoatPos - 1] = BoatPos;
The algorithms above don't take into account the array limits. So when for instance boats position is at 23 you can't obviusly go up cuz you'll exceed the array limits
Ivan** at 2007-11-11 20:59:11 >
