Print 2d array of strings in C

This article focuses on printing the words or characters in a 2d array in a most effective way.

Photo by Nikhil Mitra on Unsplash

Previously I used to print the characters in a 2D array using a nested for loop. This is not the right approach considering the time complexity. But there is a method to print a 2D array of characters using a single for loop. This method makes use of a function called puts().

First, let us see what the puts() method is?

The C library function int puts(const char *str) writes a string to stdout up to but not including the null character. A newline character is appended to the output.

Declaration

Following is the declaration for puts() function.

int puts(const char *str)

Parameters

  • str − This is the C string to be written.

Return Value

If successful, a non-negative value is returned. On error, the function returns EOF.

In the below code snippet we will be printing the 2D array of characters using two for loops.

The below example will print the strings in a single for loop using the puts() function. A new line is added by default to the strings.

Using the puts() method we can print the strings using a single for loop. Happy coding!