Functions
Throughout the tutorial I mentioned using “functions” several times.
Recall the printf() and scanf() functions for input/output
Recall the main() function
#include<stdio.h> int main(void) { int x; scanf("%d", &x); printf("You entered %d", x); return 0; }
Recall that every C program must have a main function. It outputs an integer, and can take an input argument. For this example, we’re using void for now.
When programming it’s useful to break down a program into smaller parts, it’s bad design to write an entire program in the main() function.
If you can identify a specific task that your program needs to do, a task that is used to accomplish the final project, you can break that off into its own function.
How do we write a function?
First you need to identify what your function is doing. Figure out what it has to output, and what arguments it should receive to perform the task.
Here is a prototype of a function:
output Identifier (arg1, arg2, arg3, ...);
So a function that will, for example compute the average of 2 numbers will look like the following:
double Avg (int a1, int a2);
Note that the return type is a double, since the average usually will have a decimal. The arguments are 2 integers, and the name of the function is Avg
Now we need to actually implement the function, this means writing what it does.
double Avg (int a1, int a2) { return a1 + a2 / 2; }
Recall that in main we always typed return 0 at the end, this was an indication that we got to the end and nothing went wrong.
Well here in Avg, we want to return the average of the 2 integers.
So how does this fit into our C program?
Let’s see.
#include<stdio.h> //write functions anywhere outside main! double Avg (int a1, int a2) { return a1 + a2 / 2; } int main(void) { int x1, x2; int average; scanf("%d %d", &x1, &x2); average = Avg (x1, x2) printf("You the average is %d", average); return 0; }
As you can see, outside main we are writing our function definition, inside the curly brackets is the actual body.
Than in main, we declare 2 integers and use them as parameters into the function, it returns an integer which is stored into the int variable average.
If you are paying close attention, you will point out that there is a slight error in the code.
The function Avg returns a type double. But we are assigning it to an int.
This won’t cause a compile time error, however it will lead to bad results, as the decimal place will keep getting chopped off.
To correct it, we need to change the type of average in main, to a double type variable.