Arrays and Functions
Let's get into the details of passing an array to a function.
We'll cover the following...
We'll cover the following...
Passing an array to a function
To pass an array to a function, we just have to specify the array type, followed by an array name and square brackets in the function parameters.
Example program
Let’s write a program that takes an array in its parameters.
In the program, we will traverse the array elements. If the value of an array element is less than 50, we will update the value at that index to -1.
Press the RUN button and see the output!
Press + to interact
C++
#include <iostream>using namespace std;// print_array function will print the values of an arrayvoid print_array(int number[], int size) {for (int i = 0; i < size; i++) {cout << number[i] << " ";}cout << endl;}// modify_array functionvoid modify_array(int number[], int size) {// Traverse arrayfor (int i = 0; i < size; i++) {// If value less tha 50 set it to -1if (number[i] < 50)number[i] = -1;}cout << "Values of array inside the function:" << endl;// Call print_array functionprint_array(number,size);}// main functionint main() {// Initialize size of an arrayint size = 8;// Initialize values of arrayint number[size] = {67, 89, 56, 43, 29, 15, 90, 67};cout << "Values of array before function call:" << endl;// Call print_array functionprint_array(number,size);// Call modify_array functionmodify_array(number, size);cout << "Values of array after function call:" << endl;// Call print_array functionprint_array(number,size);}
In the code above: ...