how to pass arrays by reference c++
Passing Arrays by Reference in C++
#include <iostream>
using namespace std;
void modifyArray(int (&arr)[5]) {
for (int i = 0; i < 5; i++) {
arr[i] *= 2;
}
}
int main() {
int myArray[5] = {1, 2, 3, 4, 5};
cout << "Original array: ";
for (int i = 0; i < 5; i++) {
cout << myArray[i] << " ";
}
cout << endl;
modifyArray(myArray);
cout << "Modified array: ";
for (int i = 0; i < 5; i++) {
cout << myArray[i] << " ";
}
cout << endl;
return 0;
}
Include Necessary Header File: Include the necessary header file
<iostream>
for input and output operations.Declare Function to Modify Array: Declare a function
modifyArray
that takes an array reference parameter of typeint
with size 5.Modify Array Function: In the
modifyArray
function, iterate through the array and double each element.Main Function: In the
main
function, declare an arraymyArray
with initial values.Print Original Array: Print the original array elements using a for loop.
Call modifyArray Function: Call the
modifyArray
function, passingmyArray
as the argument.Print Modified Array: Print the modified array elements using a for loop.
Return 0: Return 0 to indicate successful program execution.
This code demonstrates passing an array by reference in C++, allowing the called function to modify the original array.