C Arrays - Real-Life Examples
Real-Life Example
An array is a collection of variables of the same data type, stored contiguously in memory. This means you can access each element of the array using an index that starts from 0 and goes up to the size of the array minus 1.
Example
#include <stdio.h>
int main() {
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
float avg, sum = 0;
int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Loop through the elements of the array and accumulate the sum
for (int i = 0; i < length; i++) {
sum += ages[i];
}
// Calculate the average by dividing the sum by the length
avg = sum / length;
// Print the average
printf("The average age is: %.2f", avg);
return 0;
}.
Output
The average age is: 40.75
And in this C programm example, we create a program that finds the lowest age among different ages:
Example
#include <stdio.h>
int main() {
// An array storing different ages
p> int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Create a 'lowest age' variable and assign the first array element of ages to it
int lowestAge = ages[0];
// Loop through the elements of the ages array to find the lowest age
for (int i = 0; i < length; i++) {
// Check if the current age is smaller than current the 'lowest age'
if (lowestAge > ages[i]) {
// If the smaller age is found, update 'lowest age' with that element
lowestAge = ages[i];
}
}
// Output the value of the lowest age
printf("The lowest age in the array is: %d", lowestAge);
return 0;
}.
Output
18