Array Algorithms
Part of the Fundamentals section of Coddy's C journey — lesson 59 of 63.
Array algorithms are essential techniques for manipulating array data. Let's learn some common array operations.
Finding the maximum value in an array:
// Initialize an array
int numbers[] = {4, 9, 2, 7, 5};
// Set initial max to the first element
int max = numbers[0];// Compare with other elements
for (int i = 1; i < 5; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
// Now max contains the largest value (9)Finding the minimum value works similarly:
// Set initial min to the first element
int min = numbers[0];
// Compare with other elements
for (int i = 1; i < 5; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
// Now min contains the smallest value (2)Summing all elements in an array:
int sum = 0;
// Add each element to the sum
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
// Now sum contains the total (27)Challenge
EasyWrite a function called findAverage that calculates the average of all elements in an integer array.
The function should:
- Take an integer array and its size as parameters
- Calculate the sum of all elements
- Divide the sum by the number of elements to get the average
- Return the average as a float
After calculating the average, print the result with exactly 2 decimal places using: printf("Average: %.2f\n", average);
Cheat sheet
Common array algorithms for finding maximum, minimum, and sum values:
Finding maximum value:
int max = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}Finding minimum value:
int min = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}Summing all elements:
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}To print a float with 2 decimal places: printf("Average: %.2f\n", average);
Try it yourself
#include <stdio.h>
// Write your findAverage function here
int main() {
int size;
scanf("%d", &size);
int numbers[size];
// Read array elements
for (int i = 0; i < size; i++) {
scanf("%d", &numbers[i]);
}
// Call your function and print the result
float average = findAverage(numbers, size);
printf("Average: %.2f\n", average);
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge