In C++, when you pass an array to a function, you're actually passing a pointer to the first element of the array. This means the function receives a reference to the array, allowing it to access and modify the array's elements.
Here's how you can pass an array to a function and perform various operations:
To print the elements of an array, you can pass the array and its size to a function. Here's an example:
<#include <iostream>>
<using namespace std;>
// Function to print array elements
void printArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
printArray(numbers, size); // Pass array and its size to the function
return 0;
}
10 20 30 40 50
To find the minimum number in an array, pass the array and its size to a function that iterates through the array and determines the smallest value.
<#include <iostream>>
<using namespace std;>
// Function to find the minimum number in an array
int findMin(int arr[], int size) {
int min = arr[0];
for (int i = 1; i < size; ++i) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
int main() {
int numbers[] = {10, 20, 5, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
int min = findMin(numbers, size); // Pass array and its size to the function
cout << "The minimum number is: " << min << endl;
return 0;
}
The minimum number is: 5
To find the maximum number in an array, use a similar approach as finding the minimum, but look for the largest value.
<#include <iostream>>
<using namespace std;>
// Function to find the maximum number in an array
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; ++i) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
int max = findMax(numbers, size); // Pass array and its size to the function
cout << "The maximum number is: " << max << endl;
return 0;
}
The maximum number is: 50