COURSE TITLE: COMPUTER PROGRAMMING I
COURSE CODE: CSC 203
NAME OF LECTURER: IBHARALU, F. I.
DEPARTMENT: COMPUTER SCIENCE
1
• C FUNCTIONS
Function in C is a sub routine, a self-contained block of statements that can
be executed.
Table of Contents
- Benefits of a function in C
- Types of functions in C
- Parts of a Function
1. Function Prototype
2. Function Definition
3. Function call
2
Benefits of using functions in C
A function provides modularity, i.e, a program can be broken into a number of
small subroutines.
Function provides reusable code.
In large programs, debugging and editing is easy with the use of functions.
3
There are two types of functions in C
Built-in (Library) Functions:
These functions are part of the C library.
E.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.
To use library functions, we include the files that contain the C
header definitions.
User Defined Functions:
These functions are defined by the programmer when writing
the program.
4
Parts of a function
- Function prototype/declaration
- Function definition
- Function call
- Function prototype
Syntax:
returnDataType functionName (Parameter List)
Example:
int addition (int a, int b);
5
- Function Definition
Syntax:
returnDataType functionName (Function arguments)
{
//the body of the function
}
Example:
int addition(int a, int b, int c)
{
//Code to do the addition
int d = a + b + c;
return d;
}
6
- Calling a function in C
Program to illustrate the sum of two numbers using a user defined function
Example:
#include<stdio.h>
int sum (int a, int b); //this is the function declaration
int main()
{
int answer; //local variable definition
answer = sum(6, 12); //calling a function to get the sum of 6 & 12.
printf("The sum of the two numbers is: %d\n",answer);
return 0;
}
7
int sum (int num1, int num 2) //function returning the sum of two numbers
{
return num1+num2;
}
Program Output:
The sum of the two numbers is: 18