Home > Software design >  Print array of strings vertically
Print array of strings vertically

Time:07-04

I know how to print a single string vertically.

char test[100] = "test";
int i;
for(i=0;i<strlen(test);i  ){
    printf("%c\n",test[i]);
}

Which will give me:

t
e
s
t

But how can I print an array of strings vertically? For example:

char listOfTest[2][10] = {"testing1","quizzing"};

So it can return:

tq
eu
si
tz
iz
gi
1g

CodePudding user response:

Simply loop through the first string and print each character at index i in the first string and the second string till you reach the null terminator of first string

NOTE: this only work when string 1 and string2 are equal in length and will need modification for other test cases

#include <stdio.h>

int main(void)
{
        char listOfTest[2][10] = {"testing1","quizzing"};
        int i = 0;
        //loop through string 1 till NULL is reach
        while (listOfTest[0][i])
        {
                //prints char at index i in string 1 and 2
                printf("%c%c\n", listOfTest[0][i], listOfTest[1][i]);

                //increment the index value
                i  ;
        }

        return (0);
}

CodePudding user response:

Simply print a character from both strings.

(Better to test for the null character rather than repeatedly call strlen().)

for(i = 0; listOfTest[0][i] && listOfTest[1][i]; i  ) {
  printf("%c%c\n", listOfTest[0][i], listOfTest[1][i]);
}

To extend to n strings ...

size_t num_of_strings = sizeof listOfTest/sizeof listOfTest[0];
bool done = false;

for (size_t i = 0; listOfTest[0][i] && !done; i  ) {
  for (size_t n = 0; n < num_of_strings; n  ) {
    if (listOfTest[n][i] == '\0') {
      done = true;
      break;
    }
    printf("%c", listOfTest[n][i]);
  }
  printf("\n");
}

CodePudding user response:

Use a pointer to each string.
Advance the pointer if not at the terminating zero.
Print the character pointed to or a space.
Does not matter if the strings are the same length or not.

#include <stdio.h>

int main ( void) {
    char listOfTest[2][10] = {"testing","quizzing"};
    char *one = listOfTest[0];
    char *two = listOfTest[1];

    while ( *one || *two) {
        printf ( "%c%c\n", *one ? *one : ' ', *two ? *two : ' ');
        one  = (*one != 0); // advance pointer if not terminating zero
        two  = (*two != 0);
    }

    return 0;
}

Output:

tq
eu
si
tz
iz
ni
gn
 g
  • Related