ntrncx 19 Junior Poster

as always since i am not student i study for hobby from a book, i dont ask for code or tell me the answer only for advices to help me understand better things

its the first steps of a moving knight in a chessboard,i had to make it move randomly and print how far it went!
i have to check if its available the position and if it already been there before

the exercise is that one:
http://books.google.com/books?id=hwpqHb5NBSoC&pg=PR8&lpg=PR8&dq=how+to+program+c%2B%2B+google+books&source=bl&ots=7JDhJwfxmT&sig=oP9rZhdJ_9N56I3VMnBUw6rZ4F0&hl=en&ei=TsxmTcrUO4L-8AaQ85zrCw&sa=X&oi=book_result&ct=result&resnum=5&ved=0CC8Q6AEwBA#v=onepage&q&f=false

page 339/ 7.24 the b part

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


int main()
{
    int vertical[8]={-1,-2,-2,-1,1,2,2,1};
    int horizontal[8]={2,1,-1,-2,-2,-1,1,2};
    int board[8][8]={};
    int currentrow=3;
    int currentcolumn=4;
    int movenumber;
    int counter=0;
    int temp=0;

        srand(time(0));
        board[currentrow][currentcolumn]=0;

        for (;counter<=64;) //i am sure thats the wrong part!but i cant think a way to change it if i put for example to loop with the conditions in line 26,will do only few steps....or thats what the exercise asks?and i understood it wrong?
        {
                movenumber=rand()%8;
                currentrow+=vertical[movenumber];
                currentcolumn+=horizontal[movenumber];

            if (currentrow>=0 && currentrow<=7 && currentcolumn>=0 && currentcolumn<=7
                    && board[currentrow][currentcolumn]==0)
            {
                counter++;
                board[currentrow][currentcolumn]=counter;
            }
            else  
            {
                temp++;
                currentrow-=vertical[movenumber];
                currentcolumn-=horizontal[movenumber];
                if (temp==1000) //thats the only way that i thought to make it stop.
                    break;
            }

        }
        cout<<"\nMoves: "<<counter;

    cout<<endl<<endl;

    for (int x=0;x<8;x++)
    {
        for (int y=0;y<8;y++)
        {
            cout<<board[x][y]<<" ";
        }
        cout<<endl;
    }
}

and some general advices global variables for good practise we should put constant variables only?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.