Search code examples
carraysstringoutput-formatting

Print multidimensional array of chars


I am trying to print the below two dimensional string array in C as below:

char text[10][80] = {
    "0", "Zero",
    "1", "One",
    "2", "Two",
    "3", "Three",
    "4", "Four",
};

The output should be like this:

0 Zero
1 One
2 Two
3 Three 
4 Four 

I have written the below program:

#include <stdio.h>

int main()
{
    char text[10][80] = {
        "0", "Zero",
        "1", "One",
        "2", "Two",
        "3", "Three",
        "4", "Four",
    };
    int i, j;
    for(i=0; i<6; i++)
    {
        for(j=0; j<1; j++)
        {
            printf("%s ", text[i]);
        }
    }
    return 0;
}

It does not provide me the desired output. I have tried several ways, but no luck.


Solution

  • You can modify your loop to get desired output -

    for(i=0; i<9; i=i+2){
        printf("%s %s\n", text[i], text[i+1]);
    }
    

    This loop will print the contents of array with index i and i+1 in desired format . Like values at index 0 and 1 , 2 and 3 and so on .