Find the Minimum Value in an Array

Find the Minimum Value in a List of Numbers in C++

In this exercise, you will implement a C++ function that identifies the smallest number in a list. Finding the minimum value in a dataset is a basic yet essential operation in many algorithms and applications.

Whether you're working on data analysis, statistical computations, or algorithm development, being able to extract the lowest value is a core skill. You'll write a function that takes an array of numbers and returns the smallest one found.

By solving this challenge, you'll practice how to scan through a sequence of values, perform comparisons, and efficiently manage data stored in arrays.

Implementation Details

1. Initialization

We start by assuming the first element of the array is the minimum value. This serves as our starting reference point for comparisons.

2. Comparison

As we loop through the array, we compare the current element with our stored minimum. If the current value is smaller, it becomes the new minimum.

3. Efficiency

The algorithm has a linear time complexity, meaning it only needs to check each number exactly once to find the result.

Objective

  • 1. Create a function that receives an array and its size as parameters.
  • 2. Initialize a variable to hold the minimum value with the first element.
  • 3. Iterate through the array and compare each element with the current minimum.
  • 4. Update the minimum if a smaller value is found and return it.

Example C++ Exercise

find_minimum.cpp Arrays
#include <iostream>

using namespace std;

// Function to find the minimum value in an array
int findMinimum(int arr[], int size) {
    int minVal = arr[0]; // Start with the first element

    // Iterate through the array starting from the second element
    for (int i = 1; i < size; i++) {
        // If a smaller element is found, update minVal
        if (arr[i] < minVal) {
            minVal = arr[i];
        }
    }

    return minVal;
}

int main() {
    int numbers[] = {42, 17, 23, 8, 15, 34};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    // Call the function and display the result
    int result = findMinimum(numbers, size);
    cout << "The smallest number in the list is: " << result << endl;

    return 0;
}

Example Output:

The smallest number in the list is: 8
Related Topics
Array Traversal C++ Logic Minimum Value Algorithm Data Analysis C++ Functions Programming Exercises

Share this C++ Exercise

Help others learn basic array manipulation!

© C++ Programming Exercises. Master the art of performance coding.