Group
Functions in C++
Objective
1. Create a function that receives an array and its size as parameters.
2. Initialize a variable to hold the minimum value (start 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.
5. Return the final minimum value.
Implement a function that returns the smallest value from a list of numbers.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to find the minimum value in an array
int findMinimum(int arr[], int size) {
int min = arr[0]; // Assume the first element is the minimum
// Loop through the array starting from the second element
for (int i = 1; i < size; i++) {
// If a smaller element is found, update the minimum
if (arr[i] < min) {
min = arr[i];
}
}
return min; // Return the smallest value
}
int main() {
// Define an array of numbers
int numbers[] = {42, 17, 23, 8, 15, 34};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the array size
// Call the function and store the result
int minimum = findMinimum(numbers, size);
// Display the smallest number in the array
cout << "The smallest number in the list is: " << minimum << endl;
return 0; // End of program
}
Output
The smallest number in the list is: 8