# Lesson 18: Introduction to Functions

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)

[/spoiler]

[spoiler title=”Lesson Source Code”]

```#include <iostream>
#include <string>

using namespace std;

int main(){

//Homework -- Create a function that allows 2 variables to be set to it, multiply them together, output the result, return the outcome to main, add 5 and redisplay the outcome.
int a = 5, b = 7;

cout << "The total of " << a << " + " << b << " = " << addNumbers(a, b);

cout << endl;
system("PAUSE");
return 0;
}

//int -- return type -- return goes back to where it was called from
//addNumbers -- Name of our function
// () --Arguments
// (int x, int y) -- argument list
//{  } -- Scoping brackets

return x + y;
}
```

[/spoiler]

Homework: Create a function that allows 2 variables to be set to it, multiply them together, output the result, return the outcome to main, add 5 and redisplay the outcome.

What is a function
A function is a section of code that can be called independently from anywhere else in your program to perform a specific task or group of tasks. Functions are able to be passed variables, called “arguments” that are able to be used in the function. These variables are usually passed by “value” (meaning a copy of the variable is made and passed to the function) and in certain cases are passed by reference (meaning the item of the argument itself is passed). Pass by referent will be touched on next lesson, and later on in the series.

Function declarations are broken into 3 parts. The return type, the name, and the argument list.

The return type also dictates another piece of code. If you specify anything other than void (return nothing) as a return type, then you need to return a variable / constant of that type.

For example, the following are all valid examples of returning an int.

```//Assume we need to return an int, and x is an int.
return x;
return x+5
return 5;
return (2*4)*x;
```

A few example functions and how you could call them

```//Example functions
string returnNumberAsWord (int x){
if ( x == 1) return "one";
if ( x == 2) return "two";
if ( x == 3) return "three";
return "Your number was too high for this function"; //This will only get hit if the 3 before it didn't happen
}

char numberToletter( int x){
if (x == 1) return 'a';
if (x == 2) return 'b';
if (x == 3) return 'c';
...
if (x == 26) return 'z';
return ' '; // Will return a space if none of the above match.
}

return x+5;
}

...

int main(){
string word = returnNumberAsWord(3); // Three
char someLetter = numberToLetter(3); // c