Passing Arrays to Functions

C++BasicsInputArithmeticConditionsLoops → Array → Multidimensional Arrays → Functions → Passing Arrays to Functions

How to pass arrays into functions in C++ Construction and Examples. We can pass arrays in functions.

For example,

#include <iostream>
using namespace std;
const int num = 5; //array size
void myfunc(int myarray[]); //passing array in function
int main()
{
int data[num]={1,2,3,4,5};
myfunc(data);
}
void myfunc(int myarray[])
{
for (int i=0; i< num; i++)
{
cout << myarray[i] << endl;
}
}

The following program will ask user to insert five numbers and will show the five input numbers (for loop is used).

#include <iostream>
using namespace std;
const int num = 5;
void myfunc(int myarray[]);
int main()
{
int data[num];
myfunc(data);
for (int j = 0; j < num; j++)
{
cout << data[j] << endl; //display numbers
}
}
void myfunc(int myarray[])
{
for (int i=0; i < num; i++)
{
cout << "Please insert a number: " << endl; cin >> myarray[i]; //insert numbers
}
}

NEXT: Generating Random Numbers