Introduction

In C++, arrays are used to store data of the same type. Every programmer must know that passing Arrays to Functions in C++ is a skill.

In this blog, we will explain by examples how to pass an array of values to a C++ function.Passing Arrays to Functions in C++

An array in c++ programming

In C++, we can use the “array” keyword to create an array. The following example shows how to create and initialize a one-dimensional integer array with three elements:int numbers[] = {1, 2, 3};

We have created the numbers array and initialized it with three integers (1, 2, 3).We can also create and initialize a one-dimensional string array with three elements:string letters[] = {“a”, “b”, “c”};

We have created the letters array and initialized it with three strings (‘a’, ‘b’, ‘c’).

Passing Arrays to Functions in C++

We pass the array name as an argument to the C++ function.Take these pieces of information and this process into account:

  • Declare a C++ function.
  • The function assumes an array as its parameter.
  • The C++ function repeats through the array and shows the array value.

The syntax to pass an array to a function in C++

Syntax 1

void MathFunction(int Prime_numbers[]) {}

Syntax 2

void MathFunction(int Prime_numbers[9]) {}

Example 1

The code of the program

Passing Arrays to Functions in C++ 1

#include<iostream>#include<vector>using namespace std; void mathFunction(int Prime_numbers[9]) {for (int counter = 0; counter < 7; counter++) cout << Prime_numbers[counter] <<endl;}int main() {int Prime_numbers[9] = {2, 3, 5, 7, 11, 13, 17, 19, 23};mathFunction(Prime_numbers); return 0;}

The output of the program

output 1 syntax to pass an array to a function in C++

Example2

The code of the program

Passing Arrays to Functions in C++ 2

#include<iostream>using namespace std; void pass_array(int random_numbers[], size_t size);int main(){int random_numbers[]{11,215,3568,45,159,67,72};pass_array(random_numbers,5);return 0;}void pass_array(int random_numbers[], size_t size){for(size_t counter{0}; counter<size; counter++)cout<<random_numbers[counter]<<endl;}

The output of the program

output 2 output 1 syntax to pass an array to a function in C++

Conclusion

conclusion of the article

Passing an array to a function in C++ is not tricky. You have to know how to do it.

You can pass an array to a function by using the following syntax:void MathFunction(int Prime_numbers[9]) {}

Pin It on Pinterest

Share This