Laurand Osmeni

Let's build a faster web.


How do I pass arrays into functions in C++.

Creating a function outside the main function, the first parameter is the array itself, so passing an integer array with the square brackets, otherwise it will think it is an variable, at this point it is declared as an array, usually we also include the size of the array, because we can know how many elements are going to be in the array.

void printArray(int theArray[], int sizeOfArray)

Now lets print out each element of the array, as always we begin with x equals to 0, x is less than the size of the array. Setting equal to variable it is much easier to use instead declaring a specific number, and x++ is incremented by one.

for(int x = 0; x < sizeOfArray; x++)

Now printing out the array name.

cout << theArray[x] << endl;

I need to prototype the function so the main function can access it without errors, so I simple copy and paste it above the main function. Note the protoype requires a semicolon.

void printArray(int theArray[], int sizeOfArray);

Now I am creating a 3 integer array inside the main function.

int laurand[3] = {10, 34, 243};

I am also following with another array of 6 integers.

int landi[6] = {31, 81, 4, 11, 67, 83};

So now I am having two arrays laurand and landi, so when ever I wanna use the function which I created, simple I type in the name of the function inside the main. Inside the parameter I type only the name of the array as the square brackets are not required, because I have already created the array so when ever I pass the array name it already knows it is the array. And this is the reason I am calling this program passing arrays to functions.

Passing now the array in the function and the size of 6.

printArray(landi, 6);

Watch live in action creating the program, or scroll below to copy the entire code.

passing arrays to functions
How do I pass arrays in functions in C++.
#include <iostream> using namespace std; // Prototye. void printArray(int theArray[], int sizeOfArray); int main() { int laurand[3] = {10, 34, 243}; int landi[6] = {31, 81, 4, 11, 67, 83}; printArray(laurand, 3); return 0; } void printArray(int theArray[], int sizeOfArray){ for(int x = 0; x < sizeOfArray; x++) cout << theArray[x] << endl; }

Feel free to use the code.

Last update .

Navigate between pages.