Reputation: 27
I have a multidimensional array that stores some data, and I want to print it in a matrix form (so far no prolem), thing is I want to add a few columns and rows to make it readable. Something like this:
3 |
2 |
1 |
_ _ _
1 2 3
(the "inside square" is my actual 2d array)
My question is, what is the best way to do this?
My current code looks like this:
void printBoard(char board[N][N]) {
for (int i = N-1; i >= 0; i--) {
printf("%d %c ", i, BAR);
for (int j = 0; j < N; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
for (int l = 0; l < 2; l++) {
for(int k = -4; k < N; k++) {
if(k < 0) {
printf("%c", SPACE);
}
else {
if(l == 0) {
printf("%c ", EMDASH);
}
else {
printf("%d ", k);
}
}
}
printf("\n");
}
}
It works fine but feels rather messy. Also, if I change the size of my array to be more than 10 rows/columns, the numbers don't fit right. Is there a way to format this properly without changing the original array (the one I'm passing into the function)?
Thanks!
Upvotes: 1
Views: 122
Reputation: 5955
You can control the width of the labels (number on right side and bottom) of the graph by specifying a width specifier on the printf format strings. That way, all the labels come out the same size. You can also specify a string like "--------------" (make it long enough to print your longest bar) and just print out the number limited by a width specifier.
Example:
printf("%*s ", length, "----------------------------------------");
Upvotes: 2
Reputation: 23218
Use format specifiers and escape sequences to place text where you need it to appear. For example this code: (from a tutorial on printf and formatting)
#include<stdio.h>
main()
{
int a,b;
float c,d;
a = 15;
b = a / 2;
printf("%d\n",b);
printf("%3d\n",b);
printf("%03d\n",b);
c = 15.3;
d = c / 3;
printf("%3.2f\n",d);
}
Produces this output:
7
7
007
5.10
Of particular interest to you, as you are using integers, note the modifiers that can be used with the "%d" specifier below in the Format specifiers section:
Escape sequences:
\n (newline)
\t (tab)
\v (vertical tab)
\f (new page)
\b (backspace)
\r (carriage return)
\n (newline)
Example Format specifiers:
%d (print as a decimal integer)
%6d (print as a decimal integer with a width of at least 6 wide)
%06d (same as previous, but buffered with zeros) (added)
%f (print as a floating point)
%4f (print as a floating point with a width of at least 4 wide)
%.4f (print as a floating point with a precision of four characters after the decimal point)
%3.2f (print as a floating point at least 3 wide and a precision of 2)
Upvotes: 0