C Program to Find Minimum Value in Array (original) (raw)

Last Updated : 20 Nov, 2024

In this article, we will learn how to find the minimum value in the array.

The easiest and straightforward method is to iterate through each element of the array, comparing each value to an assumed minimum and updating it if the current value is less.

C `

#include <stdio.h>

int findMin(int arr[], int n) {

// Assume first element as minimum
int min = arr[0];
for (int i = 1; i < n; i++) {
  
      // Update m if arr[i] is smaller
    if (arr[i] < min) {
        min = arr[i]; 
    }
}
return min;

}

int main() { int arr[] = {5, 2, 7, 6}; int n = sizeof(arr) / sizeof(arr[0]);

  // Find and print minimum value in arr
printf("%d\n", findMin(arr, n));

return 0;

}

`

This method is simply the linear search algorithm modified to find the minimum element.

There are also some other ways to find the minimum value in array in C. They are as follows:

Table of Content

Recursive Method

The function reduces the search size by comparing the last element with the minimum of the remaining elements and recursively processing the rest of the array. This continues until the base case is reached, where a single element remains, which is returned as the minimum.

C `

#include <stdio.h>

// Recursive approach to find the minimum element int findMin(int arr[], int n) {

// Base case: Only one element
if (n == 1) return arr[0];

  // Find  minimum from the rest of the array
int min = findMin(arr, n - 1);

  // Return smaller element between curent element
  // or minimum element in rest of the array
return arr[n - 1] < min ? arr[n - 1] : min;

}

int main() { int arr[] = {5, 2, 7, 6}; int n = sizeof(arr) / sizeof(arr[0]);

// Finding and printing the minimum element
printf("%d\n", findMin(arr, n));

return 0;

}

`

While this approach is intuitive, it can be less efficient than iterative method for large arrays due to the space required for recursive calls.

By Sorting

In an array sorted in ascending order, the minimum element is present at the beginning (0th index). The array can be sorted using qsort() function with a custom comparator for ascending order.

C `

#include <stdio.h> #include <stdlib.h>

// Comparator function for qsort (ascending order) int compare(const void *a, const void b) { return ((int *)a - *(int *)b);
}

int findMin(int arr[], int n) {

  // Sort the array using qsort
qsort(arr, n, sizeof(int), compare);
  
  // The first element is smallest after sorting
  return arr[0];

}

int main() { int arr[] = {5, 2, 7, 6}; int n = sizeof(arr) / sizeof(arr[0]);

// Find and print the minimum element in arr
printf("%d\n", findMin(arr, n));

return 0;

}

`

This method is less efficient than linear search for just finding the minimum element but more suitable for finding the n-th smallest element.

Similar Reads