Real-Life Example of Arrays in C
Arrays are widely used in programming to handle collections of data. Below is a practical example demonstrating the use of arrays in calculating the average of student grades.
Example: Calculating Average Grades
#include <stdio.h>
#define NUM_STUDENTS 5
int main() {
    float grades[NUM_STUDENTS];
    float sum = 0.0;
    int i;
    printf("Enter grades for %d students:\n", NUM_STUDENTS);
    for (i = 0; i < NUM_STUDENTS; i++) {
        printf("Student %d: ", i + 1);
        scanf("%f", &grades[i]);
        sum += grades[i];
    }
    float average = sum / NUM_STUDENTS;
    printf("Average grade: %.2f\n", average);
    return 0;
}
Code Explanation: The program collects grades from the user, stores them in an array, calculates the sum, and computes the average grade.
Key Takeaways
- Arrays are essential for handling multiple related data items efficiently.
- Loops are commonly used to process array elements.
- Defining array size with constants improves code maintainability.