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

Print array of strings vertically

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:

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

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

So it can return:

tq
eu
si
tz
iz
gi
1g

>Solution :

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");
}
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