C Loop Statements
This chapter introduces three types of loops: for, while, do-while, as well as the usage and considerations of break/continue.
1. for Loop
c
for (int i = 0; i < n; ++i) {
// ...
}- Suitable for loops with known iteration count
2. while Loop
c
while (cond) {
// ...
}- Suitable for condition-driven loops
3. do-while Loop
c
do {
// ...
} while (cond);- Executes at least once
4. break and continue
break: Immediately ends the current loopcontinue: Skips the remaining part of the current iteration and enters the next iteration
5. Multi-level Nesting and Performance
- Try to avoid deep nesting, consider splitting into functions
- Be aware of expensive operations inside loops (like I/O)
6. Example: Finding Maximum Value in Array
c
#include <stdio.h>
int max(const int *a, int n) {
if (n <= 0) return 0;
int m = a[0];
for (int i = 1; i < n; ++i) if (a[i] > m) m = a[i];
return m;
}
int main(void) {
int arr[] = {3, 9, 4, 7};
printf("%d\n", max(arr, 4));