Possible movement of Knight in Chess.

I have to do a program where the user is asked to enter the
2D position of the Knight on the Chess board and then the
program is asked to show all the possible moves.
Ofcourse the Knight moves in L-shaped directions.
So this is the best I could,
However the professor is asking me to use ARRAY and FOR LOOP
to do the project.
I am showing you the work, so maybe you guys can help me by
adding the array code and the for loop code or at least
let me know where to put it.

Appreciated.

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
#include <iostream>
using namespace std;


void probability (int r, int c){
    
    cout<< "the probabilities are the following: " << endl;
    
    
    if (r + 2 <= 8 && c + 1 <= 8 )
    cout<< r + 2 <<"\t"<< c + 1 <<endl;
    if (r + 2 <= 8 && c - 1 <= 8 )
    cout<< r + 2 <<"\t"<< c - 1 <<endl;
    if (r - 2 <= 8 && c + 1 <= 8 )
    cout<< r - 2 <<"\t"<< c + 1 <<endl;
    if (r - 2 <= 8 && c - 1 <= 8 )
    cout<< r - 2 <<"\t"<< c - 1 <<endl;
    if (r + 1 <= 8 && c + 2 <= 8 )
    cout<< r + 1 <<"\t"<< c + 2 <<endl;
    if (r + 1 <= 8 && c - 2 <= 8 )
    cout<< r + 1 <<"\t"<< c - 2 <<endl;
    if (r - 1 <= 8 && c + 2 <= 8 )
    cout<< r - 1 <<"\t"<< c + 2 <<endl;
    if (r - 1 <= 8 && c - 2 <= 8 )
    cout<< r - 1 <<"\t"<< c - 2 <<endl;
}

int main()
{

   int r, c;
   
   cout<<"enter the raw: ";
   cin>>r;
   cout<<"enter the column: ";
   cin>>c;
   
   probability(r,c);
    return 0;
}
Last edited on
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
#include <iostream>

constexpr int N = 8 ; // board size
using board_type = bool[N][N] ; // array

bool valid( int row_or_col ) { return row_or_col >= 0 && row_or_col < N ; }

void clear( board_type& board ) { for( auto& row : board ) for( auto& v : row ) v = false ; }

void set_if_valid( board_type& board, int row, int col )
{ if( valid(row) && valid(col) ) board[row][col] = true ; }

void possibile_knight_moves( board_type& board, int row, int col )
{
    clear(board) ;

    if( valid(row) && valid(col) )
    {
        for( const int row_delta : { -2, +2 } ) for( const int col_delta : { -1, +1 } )
        { set_if_valid( board, row + row_delta, col + col_delta ) ; }

        for( const int row_delta : { -1, +1 } ) for( const int col_delta : { -2, +2 } )
        { set_if_valid( board, row + row_delta, col + col_delta ) ; }
    }
}

int main()
{
    board_type board {} ; // array

    int row, col = 0 ;
    std::cin >> row >> col ;

    possibile_knight_moves( board, row, col ) ;

    for( int row = 0 ; row < N ; ++row ) for( int col = 0 ; col < N ; ++col )
    { if( board[row][col] ) std::cout << row << ", " << col << '\n' ; }
}
Topic archived. No new replies allowed.