Real-Life Examples of Loops in C
Loops are essential in programming for automating repetitive tasks. Here are some real-life scenarios where loops are used in C programming.
Examples
1. Summing Elements in an Array
#include <stdio.h>
int main() {
int numbers[] = {2, 4, 6, 8, 10};
int sum = 0;
int i;
for (i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum of elements: %d\n", sum);
return 0;
}
2. Searching for an Element
#include <stdio.h>
#include <stdbool.h>
int main() {
int data[] = {3, 7, 1, 9, 5};
int key = 9;
bool found = false;
int i;
for (i = 0; i < 5; i++) {
if (data[i] == key) {
found = true;
break;
}
}
if (found) {
printf("Element %d found at index %d.\n", key, i);
} else {
printf("Element %d not found.\n", key);
}
return 0;
}
3. Reading Data Until End-of-File
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
int value;
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while (fscanf(file, "%d", &value) != EOF) {
printf("Read value: %d\n", value);
}
fclose(file);
return 0;
}
Key Takeaways
- Loops automate repetitive tasks and are fundamental in programming.
- Understanding different loop constructs allows you to choose the most appropriate one for a given problem.
- Real-life examples demonstrate the practical applications of loops.