two dim array for loops
Jul 16, 2012 at 7:46pm UTC
hello all. i'm having trouble trying to think of a 'formula' or 'equation', etc
its a simple 8 x 8 (64) 2 dimensional array
im printing the board through two for loops, I'm trying to emulate how a bishop can move (diagonally). I got the one working, but i cant think of a way to get the other side to work:
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
#include <iostream>
using namespace std;
enum
{
rows = 8, //across
cols = 8 //vertical
};
struct sboard
{
int arr[rows][cols];
};
void printb(sboard const *board)
{
for (int i=0;i<rows;i++)
{
int offj = 7;
for (int j=0;j<cols;j++)
{
if (i == j || (i == 0 && offj == 0))
{
cout << "X" ;
}
//cant modulus/divide by zero
else if (offj !=0 && (i % offj == 0 && i / offj == 1))
{
cout << "X" ;
}
else
{
cout << board->arr[i][j];
}
offj-=1;
}
cout << endl;
}
}
int main()
{
sboard board;
for (int i=0;i<rows;i++)
{
for (int j=0;j<cols;j++)
{
board.arr[i][j] = i;
}
}
printb(&board);
cin.get();cin.get();
return 0;
}
note that i want to be able to do this without making another for loop or function. it should fit in the else if statement. yes i feel kinda dumb
Last edited on Jul 17, 2012 at 5:53am UTC
Jul 16, 2012 at 8:06pm UTC
I guess cols - j ?
Jul 17, 2012 at 12:53am UTC
found it out.. took me a while. at least i practiced my modulus
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
for (int i=0;i<rows;i++)
{
int offj = 7;
for (int j=0;j<cols;j++)
{
if (i == j || (i == 0 && offj == 0))
{
cout << "X" ;
}
//cant modulus/divide by zero
else if (offj !=0 && (i % offj == 0 && i / offj == 1))
{
cout << "X" ;
}
else
{
cout << board->arr[i][j];
}
offj-=1;
}
cout << endl;
}
Last edited on Jul 17, 2012 at 5:54am UTC
Topic archived. No new replies allowed.