Functions allow you to perform the same operation on many inputs with one simple call.
Why a function anyways?
First of all, let’s see how we’d perform a certain task without one. How would we print out the entire contents of a vector each time we modified it? Let’s show how we would do it once.
vector vec;
//After populating our vector...
for ( int i = 0; i < vec.size(); i++ ) {
cout << vec[i] << " "; }
Are we really going to write this code every time we want to print out the contents? We don't have to. We can create a function that executes several instructions based on given inputs and produces an output. (Note: This isn't always the case) Example? Place car parts onto an assembly line, and the assembly line produces a car! Same with a function.
The function
Below is the syntax:
return_type name(parameters) {
statements
return return_type;
}
You can return data types such as strings, int, double, bool, and void (simply doesn't return anything).
So how would we make our printing of a vector a function? Quite simple.
void print(vector vec) {
for ( int i = 0; i < vec.size(); i++ ) {
cout << vec[i] << " " ; }
return;
}
Pretty simple right? Where do we place this function? I'll show you below.
#include
#include
using namespace std;
void print(vector vec) {
for ( int i = 0; i < vec.size(); i++ ) {
cout << vec[i] << " " ; }
return;
}
int main() {
vector v;
//Populate our vector
print(v); //This is where our function is called
return 0;
}
Question: But wait? Our function does not provide the same name as the one used in our program!
Answer:No worries. The function only needs to know what type of data type you'll be passing in, and it will use it accordingly to its parameters.
More examples
Let's use another return type and with more parameters.
int sumofvec(vector vec, int num) {
int sum = 0;
for ( int i = 0; i < num || i < vec.size(); i++ )
sum += vec[i];
return sum;
}
This is how we would call it in our main using a populated vector.
cout << "Sum of first 3 numbers in our vector[" << sumofvec(vec,5) << "]\n";
This would simply call our function on a vector and print out the sum of the first five numbers. If the vector doesn't have five elements, it will stop either way because of my condition.
Exercises with Functions
So what now? Try doing the following challenges.
Challenge 1: Search for a certain number in a vector. If found return true.
Challenge 2: Return a vector that has the reversed order of elements of the one passed in.
What now?
Our next tutorial on functions should show you how to use functions more efficiently and how to do more with them.
