Sometimes called a subroutine, module or procedure, a function is a group of instructions
that performs a given task. Every program in C consists of at least one function: main()
.
The idea of functions is to avoid repeating the same piece of code at different
places in the program. We write this code in a function and we call this function
each time it is needed. In the previous lessons, we have already used some functions:
printf()
scanf()
When a function is used, it is a call to a function.
The following code is a call to the print
function:
printf ("Hello");
Consider, for the example, the following function max()
which returns the larger of the two integers between a
and b
:
int max(int a, int b);
The syntax of this function is illustrated below:
Let's detail this syntax:
Writing a function is done in two parts:
Here is an example of the structure of a complete program with the implementation of a function :
#include <stdio.h>
// Prototype of the function
int max (int a, int b);
// Main function
int main(void)
{
// Call the max function
printf ("The greater is %d\n", max(12, 7));
return 0;
}
// Implementation of the function
int max(int a, int b)
{
if (a>b) return a; else return b;
}
We provide two functions addition()
and subtraction()
which return the sum and subtraction of parameters a
and b
respectively:
// Return the sum of a and b
int addition (int a,int b) {
return a+b;
}
// Subtract b from a and return the result
int subtraction (int a,int b) {
return a-b;
}
Using these functions as models, complete the program with
multiplication()
which returns the product of its two parameters:Function addition : x + y = 12 Function subtraction : x - y = 4 Function multiplication : x * y = 32
Write a program that contains a function int square (int n)
that calculates the
square of the integer n
. Test your function with the following main program:
int main(void) {
int x=8;
printf("%d*%d = %d\n", x, x, carre(x));
return 0;
}
Write a program that contains a function char parity(unsigned int n)
that returns:
0
if n
is an odd number ;1
if n
is an even number;Test the function with a main program that asks the user to enter an integer before displaying whether it is even or odd.
Enter an integer: 15 15 is even.
The function even()
should not display anything, but return 0 or 1 to the main program.
In C, a function allows
How many parameters does the following function have:
int My_function (float x, unsigned short Val);
The prototype of a function ...
The prototype of a function is located ...
The implementation of a function ...
The implementation of a function is placed ...