chapter 5 modular programming
DESCRIPTION
moduler programmingTRANSCRIPT
Chapter 5Modular
Programming
Chapter 8 : Modular Programming
2
Objectives
Introduce the following topics : The need for functions How to write functions How to call and return from functions
Stresses the use of structured programming or modular programming
Chapter 8 : Modular Programming
3
Overview C program made of one or more function,
one and only one of them must be named
main. Execution of program always starts and
ends with main, but it can call other function.
Function is used to repeat the same process with a different input or output. It might have no input or output.
A function in C can perform a particular task, and supports the concept of modular programming design techniques.
Chapter 8 : Modular Programming
4
Types of Functions
Built-in function/Pre-defined function Functions already existed in the standard
library of C. Used to carry out a number of commonly
used operations @ calculations e.g : printf();scanf();
User-defined function Programmers define their own function to
carry out various individual tasks
Chapter 8 : Modular Programming
5
User-defined Function
Must be declared and defined. Function declaration also called as
function prototype. Function definition is the body itself
contains the code needed to complete the task.
Function can be called (invoked) by specifying its name.
Chapter 8 : Modular Programming
6
User-defined Function
3 main elements in using functions: Function declaration/prototype Function definition Calling a function
Chapter 8 : Modular Programming
7Function Declaration / PrototypeSyntax :
data_type function_name (arguments);
Global function declaration if write outside of main function
Local function declaration if write inside of main function
• Compulsory• Must be
synchronizes with return data type
• Compulsory• Comply with rules
of legal identifier
• Optional (depends on case)• ONLY state types of
variables (if any)
Chapter 8 : Modular Programming
8
Example
GLOBAL FUNCTION LOCAL FUNCTION
#include <stdio.h>
void testprt (int);
main(){
...statements}
#include <stdio.h>
main(){
void testprt (int);
...statements}
Chapter 8 : Modular Programming
9
Calling FunctionSyntax :
function_name (arguments);
Example :
testprt(num); @
getnum = testprt(num);
• Compulsory• Comply with rules
of legal identifier
• Optional (depends on case)• MUST consists of constant, value
of variable or address of variable
Chapter 8 : Modular Programming
10
Function DefinitionSyntax :
data_type function_name (arguments)
{
variable declaration
return expression
}
• Compulsory• Must be
synchronizes with return data type
• Compulsory• Comply with rules
of legal identifier
• Optional (depends on case)• MUST state types and
name of variables (if any)
Chapter 8 : Modular Programming
11Structure of Function DefinitionThe body of a C function must be
enclosed between braces { }.Return value : the data type that will
be return by the function, void for no return value.
Arguments : it can contain parameters or no parameters.
Chapter 8 : Modular Programming
12
void display(int no){no = 5;
printf("\nValue for num is %d“, no);}
Example
Chapter 8 : Modular Programming
13
Example of Full Programs#include <stdio.h>
#include <conio.h>
void display (); // Function declaration / Function prototype
void main()
{
printf("\nFirst function");
display();// Calling a function
printf("\nI have finish called a function");
getch();
}
//Define a function
void display()
{
printf("\nThis is my first function");
}
Chapter 8 : Modular Programming
14
FIGURE 4-5 : Declaring, Calling and Defining Functions
Chapter 8 : Modular Programming
15
Exercise
Write a function name number that read an integer number from user and display it on the screen.
Write a function name getSum that read two integer numbers from users and display the sum on the screen.
Chapter 8 : Modular Programming
16
Basic Function Designs
1. void functions with no parameters2. void functions with parameters3. Functions that return a value but
have no parameters4. Functions that return a value and
have parameters.
Chapter 8 : Modular Programming
17void functions with no parameters
FIGURE 4-5 : void functions with no parameters
Chapter 8 : Modular Programming
18
FIGURE 4-6 void Function with Parameters
void functions with parameters
Chapter 8 : Modular Programming
19PROGRAM 4-2 void Function with a Parameter
Chapter 8 : Modular Programming
20PROGRAM 4-2 void Function with a Parameter
Chapter 8 : Modular Programming
21
FIGURE 4-7 Non-void Function without Parameters
Non-void functions without parameters
Chapter 8 : Modular Programming
22
FIGURE 4-8 Calling a Function That Returns a Value
Non-void functions with parameters
Chapter 8 : Modular Programming
23PROGRAM 4-3 Read a Number and Square It
Chapter 8 : Modular Programming
24PROGRAM 4-3 Read a Number and Square It
Chapter 8 : Modular Programming
25PROGRAM 4-3 Read a Number and Square It
Chapter 8 : Modular Programming
26PROGRAM 4-3 Read a Number and Square It
Chapter 8 : Modular Programming
27Returning Values from FunctionA function may or may not return a
value to a calling function.Terminate the function definition with
a return statement if it has a return type.
The value returned is given by the expression following the keyword return.
Use void if the function does not return any value.
Chapter 8 : Modular Programming
28
main(){
float calc(int), num;
num = calc(10);
printf (“%.2f”,num);}
float calc(int no){
float dfloat = 5;no *= dfloat;
return no;}
Example
Chapter 8 : Modular Programming
29
Exercise
Write a function name get_Sum that read two integer number from user and return the sum of these two number to the main. Display the sum at the main function.
Chapter 8 : Modular Programming
30
Exercise
Write a function based on the following criteria:
Function Name: display
Purpose : display statement “ This function return nothing”.
Called by : main
Receives : none
Returns : none
Chapter 8 : Modular Programming
31
Calling A Function
The primary function that controls function calls and their order is called a calling function.
To call function : type its name- including parentheses- follow it with semicolon.
Example : getSum(); A function call in C can appear as an
expression or it can appear an expression statement.
num = calc(10); || display();
Chapter 8 : Modular Programming
32
Calling A Function ....cont
A user defined-function can call another function.
A function can be called many times.
#include <stdio.h>
void printOne(int x);
int main(){ int a = 5;
printOne(a); a = 33; printOne(a);
return 0;}
void printOne(int x){ printf(“%d\n”,x); return;}
Chapter 8 : Modular Programming
33Exercise Calling function or called function?void main()
{ …..
display();
}
void display()
{ …….
get_sum();
}
int get_sum()
{ ……
return sum;
}
NESTED FUNCTION
Chapter 8 : Modular Programming
34Passing Arguments To Functions Variable declared in a function are local
variable. Their scope is limited to that function and
cannot be access from another function. The functions are independent of each
other. To pass value from one function to another
must use arguments or parameters.
Chapter 8 : Modular Programming
35Passing Arguments To FunctionsThe calling function passes
arguments (e.g., int,float,char) to the called function.
The called function receives and stores the argument value its parameters.
Once the values have been received into parameters, they behave like local variables declared within that function.
Chapter 8 : Modular Programming
36Passing Arguments To FunctionsThe number and type of arguments
passed to the called function must agree with the number and type of parameters in the called function.
function(arg1, arg2, arg3) Calling function
function(par1, par2, par3) Called function
Chapter 8 : Modular Programming
37
Exercise
Write a function name get_Sum that receive two integer number from main. get_Sum will add these two number and return the sum of these two number back to the main. Display the sum at main.
Chapter 8 : Modular Programming
38
Exercise
Write a function name display_Age that receive age from main. display_Age will display age and return nothing to main function.
Chapter 8 : Modular Programming
39Exercise Write an appropriate main program and two
functions based on the following criteria:
Function Name: get_Age
Purpose : get an age from user
Called by : main
Receives : none
Returns : age
Function Name: display_Age
Purpose : display an age
Called by : main
Receives : age
Returns : none
Chapter 8 : Modular Programming
40Exercise Write an appropriate main program and two
functions based on the following criteria:
Function Name: get_Age
Purpose : get an age from user
Called by : main
Receives : none
Returns : none
Function Name: display_Age
Purpose : display an age
Called by : get_Age
Receives : age
Returns : none
Chapter 8 : Modular Programming
41
INTER-FUNCTION COMMUNICATION
Chapter 8 : Modular Programming
42
Passing Pointer to a Function Passing pointer to a function is quite
similar as passing other variable. The function declaration and definition
must have the pointer declaration in their argument.
Pass the address of variable when the calling function pass call the called function.
Chapter 8 : Modular Programming
43
Examplevoid main()
{
void addcon(int *, int *); // prototypes
int x=6,y=7;
printf("\nx is %d, y is %d",x,y);
addcon(&x, &y);
printf("\nx is now %d, y is now %d",x,y);
getch();
}
void addcon(int *px, int *py)
{
*px=*px + 10;
*py=*py + 10;
}
Chapter 8 : Modular Programming
44
Passing Array to a Function A function can receive the address of an
array by using pointer. The declaration and definition for passing
array arguments is the same as passing a pointer address.
The argument send from the calling function is the name of array.
Chapter 8 : Modular Programming
45
Example#define n 5
void main()
{
int get_total(int *, int); // function prototype
int total, y[n] = {1,2,3,4,5};
total = get_total(y, n); // function call
printf("\nTotal = %d", total);
getch();
}
int get_total(int *ptr , int x) // function definition
{ int i, total=0;
for (i=0;i<x; i++)
{ total = total + *(ptr + i);
}
return total;
}
Chapter 8 : Modular Programming
46
Passing Arguments by Value In the example so far, the calling function
passed arguments (value of variables) to the corresponding parameters in the called function.
The called function then used these parameter values to do its computation.
Any changes made to these parameters in the called function did not have any effect on the variables in the calling function that passed the values since only copies or values of the arguments were passed to the called function.
Chapter 8 : Modular Programming
47
Passing Arguments by Value When only copies of arguments are passed
to a function, this is known as passing arguments by value (or passing by copy).
Chapter 8 : Modular Programming
48
Example
void modify_Number(int); // prototypes
void main()
{
int number;
printf("\nEnter an integer number: ");
scanf("%d",&number);
printf("\nNumber in main is %d",number);
modify_Number(number);
printf("\n\nNumber in main is %d",number);
getch();
}
//define a function
void modify_Number (int number)
{
number=number + 1;
printf("\n\nNumber in modify_Number is %d",number);
return ;
}
Chapter 8 : Modular Programming
49Pass Arguments by Reference Called function can change the values of
several variables in the calling function. This can be done by passing the
addressed of variables whose value that will be change from the called function.
When the called function changes the value stored in these memory addresses, the value of variables are also changed since the variables refer to same memory addresses.
Chapter 8 : Modular Programming
50Pass Arguments by ReferenceThus the address of variables from
calling function is passed to the called function to change the values of variables in the calling.
When a function passes addresses of variables to the corresponding parameters in the called function, it is called passing arguments by reference (or passing by address).
Chapter 8 : Modular Programming
51
Example
void integer_swap(int* , int*); //prototypes
void main()
{
int x=10,y=20;
printf("\nInitial values of x and y are %d %d\n",x,y);
integer_swap(&x,&y);
printf("\nSwapped values of x and y are %d %d\n",x,y);
getch();
}
//define a function
void integer_swap(int *x , int *y)
{
int temp;
temp = *x;
*x=*y;
*y=temp;
}
Chapter 8 : Modular Programming
52
Global Variable
Global variables are variable declared outside of any function.
Global variables do not belong to any specific function.
Any change made in the value of a global variable by one function will be “felt” by the other as well.
Global variables can be used for passing values to a function and returning values from it.
Chapter 8 : Modular Programming
53
Global Variable
It is not recommended to use global variable because the reader of the program does not immediately know which values are being received by the called function and which values are being returned by it.
Chapter 8 : Modular Programming
54
Built-in Function
C provides a set of commonly used function that programmers can use without having to write any code for them.
These function are called built-in, pre-defined or standard library function.
The built-in function are stored in header file.
Each header file (file with extension .h) contains functions that are related to a particular application.
Chapter 8 : Modular Programming
55
Built-in FunctionHeader file must be include before
using the functions contained in a header file.
Some of the standard header files are: stdio.h – standard I/O conio.h – screen-handling function math.h – various math function string.h – string handling ctype.h – character-handling function time.h – system time function ………
Chapter 8 : Modular Programming
56
Built-in Functionconio.h - screen-handling function
textcolor (i) textbackground (i) clrscr() gotoxy()
Chapter 8 : Modular Programming
57
Built-in Functionmath.h - various math function
sqrt (d) log10 (d) pow(d1,d2) sin(d) cos(d)
Chapter 8 : Modular Programming
58
Tips
Writing a C program, it is best NOT to sit down at the keyboard and start typing.
THINK first about the program & what it is supposed to do.
The BEST ways: start with the overall goal & divide this goal into several smaller tasks.