Home > other >  Adding a header to a 2d array
Adding a header to a 2d array

Time:02-18

Tried this but does not work as intended:

#include <stdio.h>
int main()
{
    int arr[2][2] = {10,11,12,13};
    int i,j;
    for(i = 0; i<2; i  )
    {
        printf("ds%d",i 1);
        printf("\n");

        for(j = 0; j<2; j  )
        {
            printf("%d\t", arr[i][j]);
        }
    }
    return 0;
}

The result that appeared:

ds1
10      11      ds2
12      13

The needed result should be the following:

ds1  ds2
10   11
12   13

CodePudding user response:

You need to print the header first separately.

int main()
{
    int arr[2][2] = {10,11,12,13};
    int i,j;

    /* This loop prints the headers */
    for(i = 0; i<2; i  )
    {
        printf("ds%d\t",i 1);
    }
    printf("\n");   /* new line to start printing data */

    /* This loop prints the data */
    for(i = 0; i<2; i  )
    {
        for(j = 0; j<2; j  )
        {
            printf("%d\t", arr[i][j]);
        }
        printf("\n"); /* new line after each row of data */
    }

    return 0;
}
  • Related