Search code examples
cmultidimensional-arrayprintfconversion-specifier

print equally spaced elements of a 2D array with printf


I am trying to print a 2d array that has a maximum of 3 digit numbers that are aligned when printed. For example, with a simple printf, it looks like this:

[0, 232, 20, 96, 176, 0, 0]
[0, 0, 24, 0, 0, 176, 0]
[0, 0, 0, 0, 0, 0, 0]

I would like it to be printed with all the commas aligned along the columns with additional whitespace, like this:

[   0, 232,  20,  96, 176,   0,   0]
[   0,   0,  24,   0,   0, 176,   0]
[   0,   0,   0,   0,   0,   0,   0]

How can I do this with printf?


Solution

  • You can use the width prefix to specify the minimum width for the printf conversions: printf("%4d", x); will print int variable x padded to the left with enough spaces to produce at least 4 characters.

    If you know the maximum width of any number in the array, you can hardcode this number in the format string. Otherwise you can compute the required width and use %*d and pass an extra argument to specifying the computed width.

    Here is a modified version:

    #include <stdio.h>
    
    int main(void) {
    #define M  3
    #define N  7
        int a[M][N] = {
            { 0, 232, 20, 96, 176,   0, 0 },
            { 0,   0, 24,  0,   0, 176, 0 },
            { 0,   0,  0,  0,   0,   0, 0 },
        };
    
        int width = 0;
    
        /* compute the required width */
        for (size_t i = 0; i < M; i++) {
            for (size_t j = 0; j < N; j++) {
                int w = snprintf(NULL, 0, "%d", a[i][j]);
                if (width < w) {
                    width = w;
                }
            }
        }
    
        /* print the arrays */
        for (size_t i = 0; i < M; i++) {
            printf("[");
            for (size_t j = 0; j < N; j++) {
                if (j != 0) printf(", ");
                printf("%*d", width, a[i][j]);
            }
            printf("]\n");
        }
    
        return 0;
    }
    

    Output:

    [  0, 232,  20,  96, 176,   0,   0]
    [  0,   0,  24,   0,   0, 176,   0]
    [  0,   0,   0,   0,   0,   0,   0]