When printing the matrix, insert a condition such as
if (matrix[i][j] == b)
printf("%d", b);
else
printf("%c", '\s') ;
EDIT: I'm noticing you're filling the entire matrix with 1s. You can accomplish your task with a single for loop. To help yourself figure out how to do that, try drawing the matrix (with its coordinates) on a piece of paper and write 1s in the mood right places.
memset(matrix, 0, 64*sizeof(int)); //flood fill to zeros, or whatever you want.
for(int i = 0; i < 8; i++)
{
matrix[i][i] = 1; //normal diagonal
matrix[i][7-i] = 1; //reversed diagonal
}
this may look incorrect for even numbered array sizes. You show a 5x5 which has a center, but 8x8 does NOT have a true center. It won't look the same? What do you want to do for that?
with Lehti's example, this boils down to (because we used zeros!)
if(matrix[i][j]) //abuse of the zero = false
cout << matrix[i][j]
else cout << ' '
It's happening because the array hasn't been initialized to zeroes. So if there's a stray 1 in it somewhere, your code won't set that to 0 and the 1 remains. There's probably a bunch of different values in there, but only the extraneous 1 remains.
The best thing to do is zero out the array initially when you define it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h>
int main()
{
int matrix[8][8] = {{0}}; // start with all zeroes
for (int i = 0; i < 8; i++) // put in the ones
{
matrix[i][i] = 1;
matrix[i][7-i] = 1;
}
for (int i = 0; i < 8; i++) // print
{
for (int j = 0; j < 8; j++)
printf("%d ", matrix[i][j]);
printf("\n");
}
}
you missed the memset(matrix, 0, 64*sizeof(int)); //flood fill to zeros, or whatever you want.
which is a barbaric and crude way to say
int matrix[8][8] = {{0}};
*** I very, very rarely do 2 and 3d arrays, and tend to mangle things a bit with them, I forgot the double {} initialize.
#include <iostream>
#include <cmath>
#include <bitset>
usingnamespace std;
int main()
{
constint W = 8;
for ( int M = pow( 2, W - 1 ), x = M; x > 0; x /= 2 ) cout << bitset<W>( M / x + x ) << '\n';
}
#include <iostream>
#include <string>
#include <cmath>
usingnamespace std;
string bits( int N, int W, char O, char X ) { return W ? bits( N/2, W-1, O, X ) + ( N%2 ? X : O ) : ""; }
int main()
{
constint W = 8;
constchar O = '.', X = 'x';
for ( int M = pow( 2, W - 1 ), x = M; x > 0; x /= 2 ) cout << bits( M / x + x, W, O, X ) << '\n';
}
Very nice. (Although I think 1<<(W-1) is better than pow(2,W-1).)
It doesn't work for odd sizes, though.
E.g., W = 9:
x.......x
.x.....x.
..x...x..
...x.x...
...x..... <== this x is out of place
...x.x...
..x...x..
.x.....x.
x.......x
The solution is to "or" x into M/x instead of adding it.
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <bitset>
usingnamespace std;
int main() {
constint W = 9;
for ( int M = 1 << (W - 1), x = M; x; x >>= 1 )
cout << bitset<W>( M / x | x ) << '\n';
}