hmm.. this is my source code, the assignment give said that the "X" represents an ant that moves in a 7x7 grid, but it can only move up, down, right, left 1step at a time. I've gotten my program working, but my output works most of the time. Sometimes, the first 7x7 grid on the output is distorted, it only shows a 7x3 grid. Please tell me where I have made a mistake. I'm going crazy. Help me! =( Code: #include<iostream.h> #include<conio.h> #define size 20 void main() { srand(time(0)); int box[size][size]; int i,j,y=0, count, random, key; for (i=0;i<7;i++) for (j=0;j<7;j++){ box[i][j]=y+1; y= box[i][j]; } i=3; j=3; for (count=1;;count++) { random = rand()%4; if (count==1) key= box[3][3]; else if (random==0) key= box[i][j=j+1]; else if (random==1) key= box[i][j=j-1]; else if (random==2) key= box[i=i-1][j]; else if (random==3) key= box[i=i+1][j]; if (i<0||j<0) goto out; if (i>=7||j>=7) goto out; { cout<<" "; for(int line=0;line<7;line++) cout<<"--- "; } cout<<endl; for(int k=0;k<7;k++) { for(int l=0;l<7;l++) { if(key!=box[k][l]) cout<<"| "; else if(key==box[k][l]) cout<<"| X "; } cout<<"|"; cout<<endl; { cout<<" "; for(int line=0;line<7;line++) cout<<"--- "; cout<<endl; } } cout<<endl<<endl; } out: cout<<"\nExit from program."; getch(); }
Works fine for me. >> Sometimes... When exactly? Try displaying the random seed - read time(0) into an int, display that int, then call srand with that int. That might help me reproduce the circumstances under which you observe incorrect behaviour. I don't understand why you need box[][] in this program. It contains a lookup table of the numbers 0-48 in a completely predictable fashion, so you can remove it and just calculate the position of key each time. Isn't the idea for the array to be blank except for an X, then you just display the array on each iteration? Could you show an example of the incorrect behaviour? Use code blocks to prevent it getting reformatted (and use code blocks when posting code, please).