The while loop is a control flow construct that allows you to execute a block of code repeatedly, as long as a condition is true. The syntax for a while loop is as follows:
while (condition) {
// code to execute
}
The condition expression is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop is terminated.
Here is an example of a while loop in C:
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}
In this example, the while loop iterates 10 times, from 0 to 9. The loop counter variable (i) is initialized to 0 before the loop starts, and is incremented by 1 after each iteration. The loop terminates when the value of i becomes 10 (i < 10 is false). The output of this code is “0 1 2 3 4 5 6 7 8 9”.
You can use a while loop to iterate through an array, as well. Here is an example:
#include <stdio.h>
int main() {
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int i = 0;
while (i < 10) {
printf("%d ", array[i]);
i++;
}
printf("\n");
return 0;
}
In this example, the while loop iterates through the elements of the array, and prints out the values. The output of this code is “0 1 2 3 4 5 6 7 8 9”.
You can also use a while loop to iterate through a string, as shown in the following example:
#include <stdio.h>
#include <string.h>
int main() {
char str[10] = "Hello";
int i = 0;
while (i < strlen(str)) {
printf("%c", str[i]);
i++;
}
printf("\n");
return 0;
}
In this example, the while loop iterates through the characters of the string, and prints out the values. The output of this code is “Hello”.