I need help with my program?

closed account (EApGNwbp)
this is a program to play battleship but when I enter 10 it does not display the X? can someone give me any tips? I think the error is in the second for loop?
Thanks in advance, here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

#include <iostream>
#include <ctime> 
using namespace std; 

int main()
{
    srand (time(NULL));
    const int SIZE= 10;
    char board [SIZE];
    int answer;
    fill(board, board+10, 'O');
    const int TOTAL_ATTEMPTS = 3;
    int attempts = TOTAL_ATTEMPTS;
    int index = rand() % 10;
    
    cout<<"Let's Play Battleship!!" << endl;

    for (int i=0; i<SIZE; i++)
    {
        cout << board[i] <<" ";
    }

    cout<< endl;
    
    
    

    do
    {
        cout <<"Enter a guess from 0 to 10: ";
         cin >> answer;
        if (answer >= 0 && answer < SIZE)
            board[answer] = 'X';
        

        for (int i=0; i<SIZE; i++)
        {
            cout << board[i] <<" ";
        }        
        cout<< endl; 
        
        if(answer!=index)
        {
            cout<<"You missed by Battleship!" << endl; 
        }
        if(answer==index)
        {
            cout<<"YOU SANK MY BATTLESHIP!  Well done." << endl; 
            
            cout << "GAME OVER" << endl; 
            

        }
   
    }while ( --attempts && answer != index );
    
    cout << "HA! You are out of guesses - I live to sail another day!" << endl; 
    
    cout << "GAME OVER" << endl; 
    return 0;

}
if (answer >= 0 && answer < SIZE)
board[answer] = 'X';

Your array size is 10. If you enter 10 the program checks if the answer is greater then 0, which is is, then it checks if the answer is less then the SIZE, which is 10. Since 10 is NOT less then 10, the statement evaluates to false, and the next line is never executed. what you want is:

if (answer >= 0 && answer <= SIZE)
board[answer] = 'X';

Last edited on
closed account (EApGNwbp)
@pogrady thanks!! yes I changed that but it still does not print the X when I type 10 maybe it's because the array size is from 0 to 10 and the 9th spot is the last?? Can you give me more tips thanks
The user can enter any number from 0-10 inclusive. You'll want to do something like this since your board array only has ten members :

1
2
3
4
5
std::cout << "Enter a guess from 1 to 10: ";
std::cin >> answer;
if((answer>0)&&(answer<=SIZE)) {
board[answer-1]='X';
}
Topic archived. No new replies allowed.