On these masteries I’m going to show you what are functions

in C++

,how to create one, and how to call it in your program,

Functions allow you to create “mini programs” inside your code in order to make it shorter (and better).

So, let’s recall what we did on mastery 10We will practice with the same concept, the addition of two numbers, but now we will do it with functions.

The big difference with using functions in your program is that you need to write them before our “basic code” which is the int main (). 

So, what you will need to do first is our “basic code”:

Now, if we would want the program to add two numbers that the user inputs, we could write the code inside int main (), declare the three variables (x being the first number the user inputs, y being the second number, and z being the result), then ask the user for these two variables, and then simply add them like this:

And then if we run the program, it will work like this:

And that just works fine, but it will work and look better if we use functions, and as I told you before, functions are written before int main (). So, do as follows:

  1. Write an int function called addition below “using namespace std;” Inside the parentesys you should declare your variables
  2. Return an operation that adds your two variables.

Your funtion should look something like this;

Now that you have your function, you can call it inside int main (), but you need to declare the variables inside here too. So, do as follows:

  1. Declare your two variables inside int main ()
  2. Ask the user for these two variables.
  3. Call your function using cout.

Your program now should look something like this:

Now let’s run and test it:

And that’s about it! You know now how to create a function and how to use it, congrats!

CC BY 4.0 Masteries 11 & 12 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.