Finding the smallest and largest element in an array involves scanning the array and keeping track of the minimum and maximum values encountered.
We will explore three different methods to find the smallest and largest element in an array using C.
This method iterates through the array and finds the smallest and largest elements.
#include <stdio.h> void find_smallest_largest(int arr[], int n, int *smallest, int *largest) { *smallest = *largest = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < *smallest) *smallest = arr[i]; if (arr[i] > *largest) *largest = arr[i]; } } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int smallest, largest; find_smallest_largest(arr, 6, &smallest, &largest); printf("Smallest element: %d\n", smallest); printf("Largest element: %d\n", largest); return 0; }
This method sorts the array and takes the first and last elements as the smallest and largest, respectively.
#include <stdio.h> void sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = 6; sort(arr, n); printf("Smallest element: %d\n", arr[0]); printf("Largest element: %d\n", arr[n - 1]); return 0; }
This method finds the smallest and largest element using recursion.
#include <stdio.h> void find_min_max(int arr[], int n, int *min, int *max) { if (n == 1) { *min = *max = arr[0]; return; } int temp_min, temp_max; find_min_max(arr, n - 1, &temp_min, &temp_max); *min = (arr[n - 1] < temp_min) ? arr[n - 1] : temp_min; *max = (arr[n - 1] > temp_max) ? arr[n - 1] : temp_max; } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int smallest, largest; find_min_max(arr, 6, &smallest, &largest); printf("Smallest element: %d\n", smallest); printf("Largest element: %d\n", largest); return 0; }