In this tutorial, we will explore how to pass arrays to functions in C++. By the end of this tutorial, you will be able to pass arrays to functions, manipulate array data inside functions, and understand how array data works in a function.
Prerequisites: Basic understanding of C++ syntax, function, and arrays.
In C++, arrays can be passed to functions in three different ways, namely:
When we pass an array to a function as an argument, the function works with the original array. This is because the array's address, not the actual data, is passed - this is known as 'pass by reference'.
In this example, we will pass an array to a function and print the array elements.
#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 arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size); // Pass array to the function
return 0;
}
This will output: 1 2 3 4 5
In this example, we will pass an array to a function and double the array elements.
#include <iostream>
using namespace std;
// Function to double array elements
void doubleArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
doubleArray(arr, size); // Pass array to the function
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
This will output: 2 4 6 8 10
In this tutorial, you have learned how to pass arrays to functions in C++. We have covered pass-by-value and pass-by-reference examples. You can now manipulate array data within functions and understand how this manipulation affects the original array.
Solutions:
#include <iostream>
using namespace std;
// Function to find maximum value in 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 arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Max value is: " << findMax(arr, size) << endl;
return 0;
}
#include <iostream>
using namespace std;
// Function to reverse array elements
void reverseArray(int arr[], int size) {
int start = 0, end = size - 1;
while (start < end) {
swap(arr[start], arr[end]);
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, size); // Reverse array
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Keep on practicing and experimenting with different scenarios to strengthen your understanding. Happy coding!