Problem Solving: Array and Functions

Learn to write programs using arrays and functions, with a focus on reusability.

We have seen that we may sometimes need to perform a similar kind of work repeatedly. For that, we used functions as a remedy to avoid the redundancies of the code.

Similarly, we may need to perform similar work on arrays of different sizes. How can we avoid re-writing the same or similar code?

Yes! Using functions is the answer.

Let us see how arrays can be passed as arguments into a function and how a function can use arrays as parameters in a generalized manner.

Arrays and functions

Arrays, in general, can be of different sizes; if we write a function that works on a specific size of the input, it would be problematic regarding reusability and scalability.

For example, if we want to write a function printArray() that prints the array (let’s say of size = 10) and then later, we need to print a different-sized array, (say of size = 15), the above function will be useless if it only works for size = 10.

This is one of the core reasons why arrays are not physically passed to functions. Instead, what we pass is the base address of the array and, along with that, we pass a second parameter to the function that is the size of the array; the size will dictate the function as to how much memory, from the base address onwards, the function needs to access. Look at the following example.

Get hands-on with 1200+ tech skills courses.