CBCP2202 E-Tutorial 5 Functions
CBCP2202 E-Tutorial 5 Functions
Functions
E-TUTORIAL 5
Learning Outcomes
1. Define functions and its components
2. Write function prototype, function call and function definition
3. Write C programs that invoke functions
4. Describe the use of library functions in a program
Introduction
C is a procedural language.
All program codes can be put into one function which is the main() function.
However, for larger programs this is not suitable, because the program becomes
hard to read and understand.
Functions will make sure programs are easier to read, understand and maintain.
What are functions?
Functions are segments of a program by itself that does a specific task.
All C programs have at least one function, and it is called main function.
A program in C can have many functions, but a function cannot be inside another
function.
1. Function declaration
2. Function prototype
3. Function calls
Functions in programs
Function Definition
Functions are defined as having a head and body.
{
BODY
function_body
}
Function name:
Naming a function is similar to naming a variable.
Each function has a unique name
Parameter list:
This list is made up of variable declaration of all the values to be inserted
into this function.
Function Body
The function body is made up of statements that you have learnt before, such as
declaring variables, input and output statements, selection and repetition.
In this example, the function name is display, there is no parameter list or return
values.
Function example 2:
int addition (int x, int y)
{
int total = 0;
total = x + y;
return total;
}
Question:
1. What is the return type?
2. What are the parameter list?
Complete program with functions.
#include <stdio.h>
void display_message (void);
int main()
{ OUTPUT:
printf("In function main\n"); In function main
display_message(); In function display_message
Return to function main
printf("Return to function main\n");
}
void display_message(void)
{
printf("In function display_message\n");
}
The End
Q&A
Thank you.