Easy Tutorial: Computer Programming (part 3) for DUMMIES

Hey guys! This is part 3 of my C++ tutorials. If you need to catch up on my other tutorials, here they are:

Part 1: Hello World!
https://steemit.com/programming/@charlie.wilson/easy-tutorial-computer-programming

Part 2: Variables
https://steemit.com/programming/@charlie.wilson/easy-tutorial-computer-programming-part-2-for-dummies

This tutorial is about functions. A function is a part of a program that performs a specific task. Functions are a great way to split up your code making it more easy to read and neat. Every function must have a return type, a function name, parameters, and a body.

Here is what a function looks like:

type name(parameter1, parameter2, ...)
{
/* do something */
}

More specifically...

void function(int x)
{
return x/2;
}

Return Type
A return type is what data type the function will be returning. If the function doesn't return anything, its type will be void. If you do have a return type, you must have a return statement in the function. All that looks like is simply the word return, then the value that you are returning. Example:

return x;
OR
return 3;

Name
Every function must have a unique name. This is basically the same idea as variable names.

Parameters
The function parameters are what information is passed to that function. Say you have a function that takes two integers and adds them together. Your parameters may be (int x, int y). Your function does not have to have any parameters at all though. It can just complete an independent task.

Body
The body of the function is just the code that the function executes. This will go inside two curly brackets.

Calling a Function
To call a function, you simply type the function name followed by its parameters in parenthesis. If it doesn't have parameters, you still need to include parenthesis.

One more thing before we look at some code -- You have to declare a function before you call it. The most common way to do this is putting it before the main() function.

Here is a program I wrote to give you a better idea of what functions do:

Here is the output:

I just want to point out this line:
"return (a+b+c)/2;"
Remember, the return type of this function was int. "(a+b+c)/2" evaluates to an integer.

Also, note this line:
"int average = mean(x, y, z);"
"average" is set equal to a function call. We can do this because when "mean(x, y, z)" is evaluated, an integer is returned. This matches the data type of "average."

I hope this was helpful! Feedback is very welcome!

Coin Marketplace

STEEM 0.21
TRX 0.25
JST 0.038
BTC 95686.04
ETH 3320.33
USDT 1.00
SBD 3.08