Introduction
In this lab, you will learn how to iterate through a list of strings using a while loop in the C programming language. We will declare an array of strings and then use a while loop to print each string in the array until we reach the end of the list.
Iterate a List of Strings Using a While Loop
In this lab, you will learn how to iterate a list of strings using a while loop.
Create a new file named
while-loop.cand open it in WebIDE.Copy and paste the following code into the file:
#include <stdio.h> void main() { const char* flowers[] = {"Rose", "Poppy", "Lily", "Tulip", "Marigold", NULL}; int i = 0; while (flowers[i]){ printf("%s\n\n\n",flowers[i]); ++i; } }This code declares an array of constant char pointers, named
flowers, which stores a list of strings representing different types of flowers. The array is terminated with a NULL value, which will serve as the condition for the while loop.Save the file and exit the text editor.
Compile the code using the following command in the terminal:
gcc while-loop.c -o while-loopThis command compiles the C code and generates an executable file named
while-loop.Run the program by executing the following command:
./while-loopThe program will iterate through the
flowersarray using a while loop and print each string on a new line. The loop will continue until it reaches the NULL value in the array.Observe the output of the program:
Rose Poppy Lily Tulip Marigold
The output should display each string in the flowers array on separate lines.
Summary
After completing this lab, you will be able to use a while loop to iterate through a list of strings in C. This technique can be useful when working with arrays of strings and needing to perform operations on each string individually.



