Docsity

Passing Arrays to a Function, Slides of C programming

Partial preview of the text

Download Passing Arrays to a Function and more Slides C programming in PDF only on Docsity!

Passing Arrays to a

Function

Passing Arrays as Parameters

Arrays are always passed by reference.

The โ€œ[ ]โ€ in the formal parameter

specification indicates that the variable is

an array.

It is a good practice to pass the dimension

of the array as another parameter.

If the function must not change any

element of the array then const should be

used in the formal parameter specification

of that array.

//Example 1:passing array elements to a function

#include

using namespace std;

void print_square (int);

const int ARRAY_SIZE = 5;

int main(){

int index;

int base[ARRAY_SIZE] = {3, 7, 2, 4, 5};

for(index = 0; index < ARRAY_SIZE; index++)

print_square(base[index]);

cout << endl;

return 0;

void print_square(int number) {

cout << " " << number * number;

#include //Example 2: passing a whole array using namespace std; float average (const int, int[]); int main() { const int array_size = 5; double ave; int base[array_size] = {3, 7, 2, 4, 5}; ave = average(array_size, base); cout << "The average of the numbers is " << ave << endl; return 0; }

Example 3โ€“ Function to find the sum of two arrays and

show the result in a third array

int main() { const int size = 5; double x[size] = {1.8, 2.2, 3.4, 5.1, 6.7}, y[size] = {2.0, 4.5, 1.3, 4.0, 5.5}, z[size]; add_array(size , x, y, z); cout << "Content of array z is: \n"; for (i = 0; i < size; i++) cout << "z[" << i << "] is " << z[i] << endl; return 0; }

Example 3 (cont)

// Add a[i] and b[i] and store the sum in c[i] void add_array(int size, double a[], double b[], double c[] ) { int i; // Add a[i] and b[i] and store result in c[i] for (i=0; i < size; i++) c[i] = a[i] + b[i]; } // Note that the function does not return any value

What if the array size is not in a const int? If we have an array named arr. The size of the array can be passed to the function using the following (sizeof (arr) / sizeof(arr[0]) The sizeof operator finds the total number of bytes for a variable.

#include
using namespace std;
int main()
int arr[10];
cout<<sizeof(arr); // will display 40
cout<<sizeof(arr)/sizeof(arr[0]); // will display 10

What if the array size is not in a const int?

Passing Two-Dimensional Arrays to

Functions

You can pass a two-dimensional array to a

function; however, C++ requires that the column

size to be specified in the function declaration.

#include
using namespace std;
float fun (float values[ ][4], int n);
int main()
float beans[3][4] = {
cout << fun (beans, sizeof (beans)/sizeof beans[0])<< endl;
return 0;