I got assigned to create a 1 player battleship program, and I have just started reading guides on how to program. All of the guides I have read hasnt given me any insite on how to create a 2D array for a battleship program all I know is to write:
int 2darray[10][10]
I have no clue on how to create the rest of the array =( I have 15 more days to compleate the program and I have read that you should start by doing the array. Could anybody pelase help me or link me to a guide which would be useful please? I know next to nothing about C++ but I am doing my best to learn what is needed to create the program.
int 2darray[10][10] tells the compiler to create a 10 by 10 matrix. If you don't do anything with it it is empty. You will have to fill it. Because you typed 'int' before the name of the array you can fill it with integers. I will give an example of a 2 by 2 matrix that will show the number on the first row (row 0) and the first column (column 0):
1 2 3 4 5 6 7 8 9
#include <iostream>
int 2darray[2][2] = { {1,2}, {3,4} };
int main()
{
std::cout<<2darray[0][0];
return 0;
}
With a battleship program would I need to output a char rather then a integer?
I was going to make a grid which is made up of O for the ocean X for where the bombs have missed and S for when a ship has been hit.
With the code you gave me, how would I change the "int array" so it can display characters instead of integers?
would it be like:
char array[2][2] = { {O,O}, {O,O} };
Would there also be an easier way of displaying all of the characters in the array instead of typing out:
std::cout<<array[0][0];
std::cour<<array[1][1];
etc.
Thanks
would it be like:
char array[2][2] = { {O,O}, {O,O} };
Changing 'int' to 'char' would do the trick. Now, all you have to do is put ' around the O and you are done, like this: 'O'.
I noticed that in my untested example I used your filename for an array, but my compiler is complaining that a variable can't start with a number. I renamed it to 'board' instead of '2darray':
char board[2][2] = { {'O','O'}, {'O','O'} };
Printing the whole array would probably go best using loops (such as 'for' and 'while'). As an example:
These loops work like this: The first loop goes through all the rows in the array. For each row it goes through all the columns. For each row in each column it prints 'board[row][column]'.
As you can see, 'std::cout << "\n"' is not within the brackets (the '{' and '}') of the second for-loop, meaning it will get executed for every row, but not for every column within the row. This I use to print an 'Enter' to go to the next line.
Hmm, so if I wanted to create a 10x10 grid would i have to copy and paste "{'O','O'}," like 50 times so that the
char board[10][10] = { {'O','O'}, {'O','O'}, {'O','O'}, {'O','O'},........ {'O','O'} };
has 100 value thingys?
And thanks for your help so far =)