tags:

views:

78

answers:

3

Hi

if I want to print by rows of

char boo[] = 
     "abcd"
     "efgh"
     "ijkl"
     "mnop";

I'd go with

for(i = 0; i < 4; i++)
{
  char row[] = "";
  for(j = 0; j < 4; j+)
    printf("%c", *(boo++))
  putchar('\n');
  puts(row);

}

my question is how I can print columns so I get
aeim
bfjn
cgko
dhlp

+2  A: 

Because it looks like a homework I'll just give you a clue.

Your boo is not an array of strings - preprocessor glues all adjacent string literals into one string so you got one string "abcdefghijklmnop"

You need to declare it as

char *boo[] = {"abcd", "efgh", ...};
qrdl
@qrdl -thanks but I really don't have the control over how to declar boo[]
41104
That it's a different story - you need to print 0, 4, 8, 12, then 1, 5, 9, 13 and so chars from the string. You got the point?
qrdl
The solution is obvious. You also need to put some effort into this - do not expect SO crowd to solve everything for you.
qrdl
I don't expect you to solve unless you really want to. I just wanted to put it out there so I can talk about it also to see what happens. :)
41104
+1  A: 
#include <stdio.h>

int main (int argc, char* argv[])
{
    char *boo[] = {"abcd", "efgh", "ijkl", "mnop"};
    int i, j;

    for(i = 0; i < 4; i++) {
        for(j = 0; j < 4; j++)
            printf("%c", boo[j][i]);

        printf("\n");
    }
}

-m

fogus
It looks like a homework. Why do you give a full solution?
qrdl
Because it will compile and run. What else would I give?-m
fogus
it doesn't meet the requirements anyways, OP stated in a comment that he has no control over how boo is declared.
Carson Myers
@fogus, for homework, clues--so he can learn from it and pass his course.
Carson Myers
lol this is not homework. even if I were in school this is summer break :)
41104
If people post homework questions on S.O. then it seem they care very little about learning anything.-m
fogus
+2  A: 

The other solutions involved modifying boo, which you said was against the rules, here a simple solution. Just use an inner loop which prints every 4th character relative to the outer loop.

int main() {
    int i, j;
    for(i = 0; i < 4; ++i) {
        for(j = 0; j < 4; ++j) {
            putchar(boo[i + j * 4]);
        }
        putchar('\n');
    }
}

think of it this way, this is effectivly manually treating boo as if it were a 2d array of characters. Since the formula for indexing a 1d array with 2d is (x + y * width), you can imagine that i is the x-coord and j is the y-coord.

Evan Teran
@Evan Teran - thanks,, looks like a better approach
41104
no prob, in fact if you want to print things the old way, simply switch the i and j in the putchar statement :-P.
Evan Teran