Beginners Guide to C++ Programming - Part 4

Even More Functions - Generating Random Numbers

In the last tutorial we talked briefly about functions. Since practice makes perfect we are going to review how to declare a function.

return type name (parameters)
{
statement;
}

The return type of a function is much like a variable type. If you can recall we talked about these in part 1. The return type for a function is basically what type of value we will be returning to main after the function is complete. Take this function for
 example:

int Add (int x, int y)
{
int sum;
sum=x+y;
return sum;
}
Return Type:
As you can see this basic function adds two variables (x and y) and returns the sum of them to the main function. These values are numbers, or integers, which is why we have the return type set as an int. All functions must have a return type in order for the compiler to run the code without giving you errors.

Function Name:
The function name can be anything you want it to be, so long as it follows the naming rules. In the above example I named the function for what it does, add.

Parameter:
In order for the function to be able to add anything it has to receive two variables. As you can see we used x and y to hold the values of the variables that were passed from main to the Add function.

Statement:
The statements we used was the actual declaration of a new variable (sum), and mathematical equation to add the two variables together (sum=x+y) and the return statement (return sum). The bulk of the statement should contain all the code that you want your function to execute.

Functions are the ‘meat and potatoes’ of C++ programming. I highly recommend you try setting up functions of your own and practice, practice, practice. Keep practicing until you can do it with your eyes closed.

Rand():
Continuing on with this tutorial we are going to go over a built in function. There are several built in functions that C++ has, for now we are just going to go over a rather important one, the random number generating function.

Related information
  • Generating random numbers is used more for simulation and is an important function for making games.
  • Remember how to modify the rand() function and generate random numbers in a range that you need.
  • Functions are the 'meat and potatoes' of the C++ language. Lean to use them correctly.