You are on page 1of 58

Chapter 5

Modular Programming

Chapter 8 : Modular Programming

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

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

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

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

User-defined Function

3 main elements in using functions:


Function declaration/prototype Function definition Calling a function

Chapter 8 : Modular Programming

Function Declaration / Prototype

Syntax :
data_type function_name (arguments);

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)

Global function declaration if write outside of main function

Local function declaration if write inside of main function

Chapter 8 : Modular Programming

Example
GLOBAL FUNCTION #include <stdio.h> void testprt (int); main() { } LOCAL FUNCTION #include <stdio.h> main() { void testprt (int);

...statements

...statements

Chapter 8 : Modular Programming

Calling Function

Syntax :
function_name (arguments);
Compulsory Comply with rules of legal identifier Optional (depends on case) MUST consists of constant, value of variable or address of variable

Example :
testprt(num); @

getnum = testprt(num);

Chapter 8 : Modular Programming

10

Function Definition

Syntax :
Compulsory Comply with rules of legal identifier Optional (depends on case) MUST state types and name of variables (if any)

Compulsory Must be synchronizes with return data type

data_type function_name (arguments) { variable declaration return expression }

Chapter 8 : Modular Programming

11

Structure of Function Definition


The 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

Example
void display(int no) { no = 5; printf("\nValue for num is %d, no); }

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. 2.

void functions with no parameters void functions with parameters

3.
4.

Functions that return a value but have no parameters Functions that return a value and have parameters.

Chapter 8 : Modular Programming

void functions with no parameters

17

FIGURE 4-5 : void functions with no parameters

Chapter 8 : Modular Programming

void functions with parameters

18

FIGURE 4-6 void Function with Parameters

Chapter 8 : Modular Programming

PROGRAM 4-2 void Function with a Parameter

19

Chapter 8 : Modular Programming

PROGRAM 4-2 void Function with a Parameter

20

Chapter 8 : Modular Programming

Non-void functions without parameters

21

FIGURE 4-7 Non-void Function without Parameters

Chapter 8 : Modular Programming

Non-void functions with parameters

22

FIGURE 4-8 Calling a Function That Returns a Value

Chapter 8 : Modular Programming

PROGRAM 4-3

Read a Number and Square It

23

Chapter 8 : Modular Programming

PROGRAM 4-3

Read a Number and Square It

24

Chapter 8 : Modular Programming

PROGRAM 4-3

Read a Number and Square It

25

Chapter 8 : Modular Programming

PROGRAM 4-3

Read a Number and Square It

26

Chapter 8 : Modular Programming

27

Returning Values from Function


A 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

Example
main() { float calc(int), num; num = calc(10);
printf (%.2f,num); } float calc(int no) { float dfloat = 5; no *= dfloat; return no; }

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
Receives Returns

: main
: none : 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); void printOne(int x){ int main(){ int a = 5; printOne(a); } printf(%d\n,x); return; return 0; }

a = 33; printOne(a);

Chapter 8 : Modular Programming

Exercise

{ } void display() { } int get_sum() { } return sum; . get_sum();

33

Calling function or called function?


.. display();

void main()

NESTED FUNCTION

Chapter 8 : Modular Programming

34

Passing 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

35

Passing Arguments To Functions


The 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

36

Passing Arguments To Functions

The 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)
function(par1, par2, par3)

Calling function
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

Exercise

39

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

Exercise

40

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

Example
void 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);


getch(); }

// function call

printf("\nTotal = %d", total);

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 //define a function void modify_Number (int number) void main() { int number; number=number + 1; printf("\n\nNumber in modify_Number is %d",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(); }

return ;

Chapter 8 : Modular Programming

49

Pass 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

50

Pass Arguments by Reference


Thus 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 //define a function void integer_swap(int *x , int *y) void main() { int x=10,y=20; int temp; temp = *x; 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(); } *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, predefined 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 Function

Header 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 Function

textcolor

conio.h - screen-handling function


(i) textbackground (i) clrscr() gotoxy()

Chapter 8 : Modular Programming

57

Built-in Function

sqrt

math.h - various math function


(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.