Finding the maximum and minimum values in an array is a fundamental operation in programming, often encountered when analyzing data. In this tutorial, we’ll explore how to accomplish this task using straightforward code examples.
#include <stdio.h>
int main() {
// Declare an integer array
int numbers[] = {10, 5, 20, 8, 15};
// Calculate the number of elements in the array
int count = sizeof(numbers) / sizeof(numbers[0]);
// Initialize variables to store the maximum and minimum values
int max = numbers[0]; // Assume the first element is the maximum
int min = numbers[0]; // Assume the first element is the minimum
// Loop through the array to find the maximum and minimum values
for (int i = 1; i < count; i++) {
// Check if the current element is greater than the current maximum
if (numbers[i] > max) {
max = numbers[i]; // Update the maximum value
}
// Check if the current element is smaller than the current minimum
if (numbers[i] < min) {
min = numbers[i]; // Update the minimum value
}
}
// Display the maximum and minimum values
printf("Maximum element in the array: %d\n", max);
printf("Minimum element in the array: %d\n", min);
return 0;
}
Here’s how the program works:
- We declare an integer array called
numbersand initialize it with some values. - We initialize two variables,
maxandmin, to store the maximum and minimum values, respectively. We assume that the first element in the array is both the maximum and minimum initially. - We use a
forloop to iterate through the array starting from the second element (index1). We skipped the element at index0since we’ve already assumed that the first element is the maximum and minimum. - Inside the loop, we compare each element with the current maximum and minimum values.
- If an element is greater than the current maximum, we update the
maxvariable. - If it’s smaller than the current minimum, we update the
minvariable.
- If an element is greater than the current maximum, we update the
- Finally, we display the maximum and minimum values found in the array.