C++ Array To Function

Hi everyone, inside this article we will see about C++ Array To Function.

In C++, an array can be passed as an argument to a function. When an array is passed to a function, a pointer to the first element of the array is passed to the function, along with the size of the array. This allows the function to access and manipulate the elements of the array.

Example #1

Here is an example program that demonstrates how to pass an array to a function in C++:

#include <iostream>

using namespace std;

// Function to print the elements of an array
void printArray(int arr[], int size) {
  for (int i = 0; i < size; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
}

int main() {
  int arr[] = {1, 2, 3, 4, 5};

  // Pass the array to the printArray function
  printArray(arr, 5);

  return 0;
}

In this program, we declare an array called arr with 5 elements. We then define a function called printArray that takes an array and its size as arguments and prints the elements of the array. In the main function, we call the printArray function and pass it the arr array and its size as arguments.

The output of this program will be:

1 2 3 4 5

In this example, we passed the arr array to the printArray function by simply passing the name of the array and its size as arguments. Inside the printArray function, the elements of the array are accessed using a loop and printed to the console.

Example #2

How To Print array elements using Array to function concept:

#include <iostream>
using namespace std;

void printArray(int arr[5]);

int main()
{
  int arr1[5] = {10, 20, 30, 40, 50};
  int arr2[5] = {5, 15, 25, 35, 45};
  printArray(arr1); // passing array to function
  printArray(arr2);
}

void printArray(int arr[5])
{
  cout << "Printing array elements:" << endl;
  for (int i = 0; i < 5; i++)
  {
    cout << arr[i] << "\n";
  }
}

The output of this program will be:

Printing array elements:
10
20
30
40
50
Printing array elements:
5
15
25
35
45

We hope this article helped you to understand about C++ Array To Function in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.