1

I'm trying to get the following output from the given array

 Apples      200   Grapes      900 Bananas  Out of stock
 Grapefruits 2     Blueberries 100 Orangess Coming soon
 Pears       10000

Here's what I came up so far (feels like I'm overdoing it), however, I'm still missing something when padding the columns. I'm open to any suggestions on how to approach this.

#include <stdio.h>
#include <string.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
char *fruits[][2] = {
    {"Apples", "200"},
    {"Grapes", "900"},
    {"Bananas", "Out of stock"},
    {"Grapefruits", "2"},
    {"Blueberries", "100"},
    {"Oranges", "Coming soon"},
    {"Pears", "10000"},
};

int get_max (int j, int y) {
    int n = ARRAY_SIZE(fruits), width = 0, i;
    for (i = 0; i < n; i++) {
        if (i % j == 0 && strlen(fruits[i][y]) > width) {
            width = strlen(fruits[i][y]);
        }
    }
    return width;
}

int main(void) {
    int n = ARRAY_SIZE(fruits), i, j;
    for (i = 0, j = 1; i < n; i++) {
        if (i > 0 && i % 3 == 0) {
            printf("\n"); j++;
        }
        printf("%-*s ", get_max(j, 0), fruits[i][0]);
        printf("%-*s ", get_max(j, 1), fruits[i][1]);
    }
    printf("\n"); 
    return 0;
}

Current output:

Apples      200          Grapes      900          Bananas     Out of stock 
Grapefruits 2            Blueberries 100          Oranges     Coming soon  
Pears       10000 
2
  • What's not working? The current output would be handy. Commented Nov 25, 2012 at 6:17
  • @therefromhere: current output updated. Commented Nov 25, 2012 at 6:22

2 Answers 2

2

You are computing widths wrong. In essence, you want to be able to compute the width of a particular column. Thus, in your get_max function, you should be able to specify a column. We can then pick out the elements from the list based on whether their index mod 3 is equal to the column. This can be accomplished as such:

int get_max (int column, int y) {
    ...
        if (i % 3 == column /* <- change */ && strlen(fruits[i][y]) > width) {
    ...
}

Then in your main loop, you want to choose the widths of the columns based on what column you are currently in. You can do that by taking the index mod 3:

for (i = 0, j = 1; i < n; i++) {
    ...
    printf("%-*s ", get_max(i % 3 /* change */, 0), fruits[i][0]);
    printf("%-*s ", get_max(i % 3 /* change */, 1), fruits[i][1]);
}

This should work as you expect.

Sign up to request clarification or add additional context in comments.

1 Comment

That's what I was missing. Thanks!
0

I dint try understanding your logic but i think you can space the data using tab with "\t":

printf("%s \t %d","banana", 200);

1 Comment

That won't always align things properly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.