What is a Function?
This lesson will define what functions are and why they should be used.
We'll cover the following...
A Simple Example
Consider the code below which computes the sum of all the integers in an array:
We can immediately notice that the code for computing the sum of its elements is pretty redundant. We set up a for loop each time and traverse through the array. In general, the code looks unclean.
What if there was a shortcut to compute the sum of an array in a single command? Perhaps, something like this:
That looks much cleaner! The sumArray command mysteriously returns the sum of the array. sumArray is an example of a function.
The Definition of a Function
A function is a set of statements that performs operations in a program.
In the example above, our function, sumArray, handles the for loop that adds each element of the array to the total sum.
Why do We Use Functions?
In the example above, we do not need to write the code for finding the sum over and over again. The function does it for us. That is the beauty of functions in C++!
Functions save us a lot of time and make our code cleaner. They act as templates for code we need to write repeatedly. This is the main reason we use functions.