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;
}
  1. Include Necessary Header File: Include the necessary header file <iostream> for input and output operations.

  2. Declare Function to Modify Array: Declare a function modifyArray that takes an array reference parameter of type int with size 5.

  3. Modify Array Function: In the modifyArray function, iterate through the array and double each element.

  4. Main Function: In the main function, declare an array myArray with initial values.

  5. Print Original Array: Print the original array elements using a for loop.

  6. Call modifyArray Function: Call the modifyArray function, passing myArray as the argument.

  7. Print Modified Array: Print the modified array elements using a for loop.

  8. 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.