How to loop through a string array in C

Array of Strings C Program

In C programming, a single string is an array of characters.

In fact, an array of strings is an array of character arrays.

Each element of an array of strings is a character array.

It allows to store and manipulate multiple strings.

You can iterate over the elements of a string array.

Create an array of strings

An array of strings has been created in one line using array declaration syntax in the following example:

Examples of creating an array of strings

1. const char* fruits[] declares an array of character pointers. const char* means "pointer to a constant character". fruits[] declares an array named fruits.

2. The array is initialized with the string literals "Apple", "Banana", "Cherry", "Orange", and "Watermelon".

The array can be used to access and manipulate these strings.

Loop (iterate) through a string array in C

In C programming, you can loop through a string array in C as demonstrated in the following example:

Example of looping through an array of strings
Output of the above example
Apple
Banana
Cherry
Orange
Watermelon

Explanation of Example:

1. const char* fruits[] = { "Apple", "Banana", "Cherry", "Orange", "Watermelon" };: The line declares an array of string using array of character pointers and initializes the array with the string literals "Apple", "Banana", "Cherry", "Orange", and "Watermelon".

2. int numFruits = sizeof(fruits) / sizeof(fruits[0]);: The line calculates the number of elements (length of array) in the 'fruits' array to use it in the 'for' loop.

3. for (int i = 0; i < numFruits; i++): The line uses for loop to iterate over the elements of the array.

4. printf("%s\n", fruits[i]); : It prints the element of the 'fruits' array on the basis of array index at each iteration. '%s' is the formatter for string.

Live Code Playground

In the following C code editor, you can practice by creating more arrays of strings. Click the 'Execute Code' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output