Iterating String Array with C While Loop

CCBeginner
Practice Now

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.

  1. Create a new file named while-loop.c and open it in WebIDE.

  2. 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.

  3. Save the file and exit the text editor.

  4. Compile the code using the following command in the terminal:

    $ gcc while-loop.c -o while-loop

    This command compiles the C code and generates an executable file named while-loop.

  5. Run the program by executing the following command:

    $ ./while-loop

    The program will iterate through the flowers array 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.

  6. 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.

Other C Tutorials you may like