Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a header to a 2d array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ds1  ds2
10   11
12   13

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading