In this lab, you will learn how to iterate a list of strings using a while loop.
-
Create a new file named while-loop.c
and 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-loop
This command compiles the C code and generates an executable file named while-loop
.
-
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.
-
Observe the output of the program:
Rose
Poppy
Lily
Tulip
Marigold