minimum value in array using c++
Code to Find the Minimum Value in an Array Using C++
#include <iostream>
int findMinValue(int arr[], int size) {
int minValue = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < minValue) {
minValue = arr[i];
}
}
return minValue;
}
int main() {
int array[] = {5, 3, 8, 2, 1};
int size = sizeof(array) / sizeof(array[0]);
int minVal = findMinValue(array, size);
std::cout << "The minimum value in the array is: " << minVal << std::endl;
return 0;
}
Explanation:
Include Necessary Library: The code includes the iostream library to enable input and output stream operations.
Define findMinValue Function: A function named findMinValue is defined, which takes an integer array and its size as parameters. It iterates through the array to find the minimum value and returns it.
Initialize minValue: The variable minValue is initialized with the first element of the array.
Iterate Through Array: A for loop is used to iterate through the array starting from the second element.
Check for Minimum Value: Inside the loop, each element is compared with the current minimum value, and if it is smaller, it becomes the new minimum value.
Return Minimum Value: After the loop, the minimum value is returned by the function.
Main Function: In the main function, an array of integers is defined, and its size is calculated using the sizeof operator.
Call findMinValue Function: The findMinValue function is called with the array and its size as arguments, and the result is stored in minVal.
Output Result: The minimum value is then printed to the console using cout.
Return 0: The main function returns 0 to indicate successful execution.