Programming in C: Functions

Now that you have learned about variablesloops, and if statements, it is time to learn about functions. Functions are a block of code that performs a number of predefined instructions to accomplish something productive. You can use a built-in function by importing it or you can create your own.

You have already seen functions before, namely the main function we have been using from day one. In general, functions that we write as programmers require a prototype, which is the declaration of the function. In general a prototype will consist of three main parts, the return type, the function name, and the function's arguments. Here is the general format of a function's prototype:

return_type function_name (arg_type arg1, ..., arg_type argN); 

The return type of a function tells the compiler the type of the final value that the function will output/return. If the function does not return anything than you set the return type to void

The arguments are composed of two parts, the arg_type and the arg. The arg_type is the type of the argument -- for example int, char, or double. A functions can have one or more arguments or no arguments at all.

Here is an example of a function with multiple arguments:

/* This function calculates the value of some number to some power, given both as arguments. */
int pow (int number, int power);

The prototype of the function is declared at the top of the program, normally under any includes or defines and ends in a semi-colon. Without the semi-colon the complier thinks you are starting the definition of the function. Here is an example of the pow function, declared and defined, in a program.

#include <stdio.h>
/* This function calculates the value of some number to some power, given both as arguments. */
int pow (int number, int power);
int main()
{
int x;
int y;

printf("Please input a number the power of the value you want to take (separated by a space): ");
scanf("%d", &x);
scanf("%d", &y);
printf("%d to the power of %d is %d\n", x, y, pow(x, y));

  return 0; 
}

int pow(int number, int power)
{
int sum = 1;
int i;

for(i = 1; i <= n; i++)
{
sum *= x;
}
return sum;
}

If your function is a void function than you will not include a "return;" statement at the end.

There are many reasons why programmers use functions, but most importantly it is to make our lives easier. Imagine you had to calculate a number to a power several times in your program, instead of retyping the code, you make a function and call that function with the appropriate parameters each time you want to use it.

More tutorials coming soon! Let me know how you like the tutorials by commenting below and if there is any specific topics or languages you would like covered. Follow me on Twitter to keep up-to-date on all the latest news and tutorials.

Programming in C: Switch Case Statements

Programming in C: While Loop