Sie sind auf Seite 1von 32

MODULAR PROGRAMMING

Modular Programming
Zarina Tukiran
Dept. of Computer Engineering Faculty of Electrical & Electronic Engineering Email: zarin@uthm.edu.my Office No.: 07-4537566

Sem II Session 2012/2013

MODULAR PROGRAMMING

Objectives :
understand the programming. concept of modularity in

introduce the common functions available in the C++ standard library. able to write a user-defined function in C++.

Sem II Session 2012/2013

MODULAR PROGRAMMING

Introduction
The C++ program describes in Chapter 1 through Chapter 3 uses only the function main; the programming instructions are packed into one function.
This technique, however, is good for a short program. For large program, it is not practical to put the entire programming instructions into one function. It must be broke into manageable pieces (modules / subroutines) called functions.

Sem II Session 2012/2013

MODULAR PROGRAMMING

Hierarchical modular design technique


Modularization (divide and conquer)
The complexity of design in broken down (divided) into a hierarchy of modules/routines; from general (top) to specific (bottom). Benefits: Focus on a single module at a time. Create customised low-level modules for design reuse. Avoid the repetition of writing out the same segment of code. 4 Sem II Session 2012/2013

MODULAR PROGRAMMING

Hierarchical modular design technique (cont)


Top-down decomposition partitions the system into smaller subsystems up to a level which the subsystems can be realised.
Bottom-up composition integrates and connects available modules to form bigger, more complex subsystems.

Sem II Session 2012/2013

MODULAR PROGRAMMING

Sem II Session 2012/2013

MODULAR PROGRAMMING

Categories of Functions
There are two types of functions: Predefined function User-defined function

Sem II Session 2012/2013

MODULAR PROGRAMMING

Pre-defined function
Review a concept from a algebra course.
In algebra, a function can be considered a rule or correspondence between values, called the functions arguments, and the unique value of the function associated with the arguments. Thus, if f(x)=2x+5, then f(1)=7, f(2)=9, and f(3)=11, where 1,2 and 3 are the arguments of f, and 7, 9 and 11 are the corresponding values of the function f.

Sem II Session 2012/2013

MODULAR PROGRAMMING

Pre-defined function (cont)


In C++, the concept of a function, either predefined or userdefined, is similar to that of a function in algebra. For example, every function has a name and depending on the values specified by the user, it does some computation. Some of the predefined mathematical functions are pow(x,y), sqrt(x) and floor(x).
In C++, predefined functions are organized into separate libraries. For example, the header file iostream contains I/O functions and the header file cmath contains math functions.

Sem II Session 2012/2013

MODULAR PROGRAMMING

Pre-defined function (cont)


Table below lists some of the predefined functions, the name of the header file in which each functions specification can be found, the data type of the parameters and the function type. The function type is the data type of the final value returned by the function.
Function ceil (x) cos (x) exp (x) tolower(x) topupper(x) Header File <cmath> <cmath> <cmath> <cctype> <cctype> Purpose Returns the smallest whole number that is not less than x: ceil (56.34)=57.0 Returns the cosine of angle x: cos(0.0)=1.0 Returns ex, where e=2.718: exp (1.0)=2.71828 Returns the lowercase value of x if x is uppercase; otherwise, returns x Returns the uppercase value of x if x is lowercase; otherwise, returns x
Sem II Session 2012/2013

Parameter(s) type double double (radians) double int int

Result double double double int int


10

MODULAR PROGRAMMING

User-defined function
C++ does not provide every function that we will ever need and designers cannot possibly know a users specific needs, we need to write our own functions this is called userdefined functions.
User-defined functions in C++ are classified into two categories: value-returning functions functions that have a return type. These functions return a value of a specific data type using the return statement. void functions functions that do not have a return type. These functions do not use a return statement to 11 return a value. Sem II Session 2012/2013

MODULAR PROGRAMMING

Function Elements
There are three function elements: Function definition Function call Function prototype

Sem II Session 2012/2013

12

MODULAR PROGRAMMING

Function Elements: Function Definition


General syntax
returnValueType functionName (formal parameters list) { /*function body*/ }

Sem II Session 2012/2013

13

MODULAR PROGRAMMING

Function Elements: Function Definition (cont)


Example 1 (value-returning function)
Return Value Type
Function name

Pictorial view of valuereturning function

int a int b add int sum


14

int add (int a, int b) { Formal parameter list int sum; sum = a + b; return sum; }
Sem II Session 2012/2013

MODULAR PROGRAMMING

Function Elements: Function Definition (cont)


Example 2 (value-returning function)
Return Value Type Function name

Pictorial view of valuereturning function

double circleArea( ) { Empty formal parameter list doube r, area; const double PI=3.142; cout<<Enter radius:; cin>>r; area=PI*(r*r); return (area); Sem II Session 2012/2013 }

circleArea double area

15

MODULAR PROGRAMMING

Function Elements: Function Definition (cont)


Example 3 (void function)
Return Value Type Formal parameter list

Pictorial view of void function

Function name

char letter

int n

void decide (char letter, int n) { if ((letter == A) && (n==100)) cout<<Good; else cout<<Try it again! }
Sem II Session 2012/2013

decide

16

MODULAR PROGRAMMING

Function Elements: Function Definition (cont)


Example 4 (void function)
Return Value Type Function name

Pictorial view of void function

void circleArea( ) { Empty formal Parameter list doube r, area; const double PI=3.142; cout<<Enter radius:; cin>>r; area=PI*(r*r); cout<<Area circle is << area; Sem II Session 2012/2013 }

circleArea

17

MODULAR PROGRAMMING

Function Elements: Function Call


A function is executed if it is called or invoked. In C++, the function calls can be called by : The main function User-defined function user-defined function call other user-defined function Call itself (recursion method) There are two ways to call/invoke a function: call-by-value call-by-reference
Sem II Session 2012/2013 18

MODULAR PROGRAMMING

Function Elements: Function Call


General Syntax:
(a) use the following format for value-returning function.
variableName = functionName (list of actual parameters); Example 5: (call-by-value)

y = findMin (a, b);

Sem II Session 2012/2013

19

MODULAR PROGRAMMING

Function Elements: Function Call (cont)


(b) use the following format for void function
functionName (list of actual parameters); Example 6: (call-by-value)

view (x);
Example 7: (call-by-reference)

calculate (&num, &x, &y);

Sem II Session 2012/2013

20

MODULAR PROGRAMMING

Function Elements: Function Call (cont)


Call-by-value The value holds by actual parameter is copied to the formal parameter. If the variable within the function is modified then upon return from the function, the value of actual variable is not modified.
Call-by-reference The address of actual parameter is copied to the formal parameter. If the variable within the function is modified then the value of actual variable is modified.
Sem II Session 2012/2013

21

MODULAR PROGRAMMING

Function Elements: Function Prototype


The function prototype is an important feature. tells the compiler what type of value the function returns, number and types of parameters, and order in which these parameters are expected. must added to a C++ program before the main function, if call the function before defining it. is not needed in a C++ program if the function is called after function definition.

Sem II Session 2012/2013

22

MODULAR PROGRAMMING

Function Elements: Function Prototype (cont)


General syntax
returnValueType functionName (formal parameters list) ; Example: bool accept (char let1, char let2) ; More examples: void display () ; void gName (float m) ; double temp (float t1, float t2) ; float dSeries (float r[]) ;
Sem II Session 2012/2013 23

MODULAR PROGRAMMING

Given the following.


Lets say you have the following function definition
float op (float a, float b) { int m; m=a/b; return m; } } void mul (int z) { int m; m=z*5; cout<<m is <<m;

and the function calls are as follows.

j=op(a,b);
mul (z); The function prototypes are as follows: float op (float a, float b);
Sem II Session 2012/2013

void mul (int z);


24

#include <iostream>

MODULAR PROGRAMMING

using namespace std;

float oper (float a, float b); //function prototype of op

Thus, the full program:

void mul (int z); //function prototype of mul


//===========main function====================== void main(){

float j;

j=oper (2.4,2.0); //function call to op


cout<< The j is << j << endl;

mul (100); //function call to mul


} //end of main //===========function definition of mul=============

void mul (int z) {


int m; m=z*5; cout << m is << m; } //end of mul //===========function definition of op=============

float oper (float a, float b){


int m;
m=a/b; return m; Sem II Session 2012/2013 } //end of op 25

MODULAR PROGRAMMING

ADDITIONAL: Custom Header File


Programmer can create custom header files
should end in .h e.g. myfunctionlib.h

To insert the custom header file in a C++ program using pre-processor directive. Example: #include myfunctionlib.h

Sem II Session 2012/2013

26

MODULAR PROGRAMMING

Practice

Sem II Session 2012/2013

27

MODULAR PROGRAMMING

Exercise 1: Familiarise the concept


Write C++ statements that provide a function definition, call and prototype for the following description. 1. A user-defined function named myWish which able to display I want grade A for C++ only once. 2. A user-defined function named repeatWish which able to display I want grade A for C++ 10 times. 3. A user-defined function named minus which able to find the subtraction of three numbers. 4. A user-defined function named FindMax which able to determine the highest value of two integer numbers.
Sem II Session 2012/2013 28

MODULAR PROGRAMMING

Exercise 2: Implementation of concept in the program


Now, integrate all user-defined function (Exercise 1) in a single C++ program.

Sem II Session 2012/2013

29

MODULAR PROGRAMMING

Exercise 3: More Programming


Write C++ program for each problem statements. Implement modular programming in your program.
Problem Statement 1: Counting positive and negative numbers and computing the average of numbers. Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number. Here is a sample run:

Enter integer value, the program exit if the input is 0. 1 2 -1 3 0 The number of positives is 3 The number of negatives is 1 The total is 5 The average is 1.25
Sem II Session 2012/2013 30

MODULAR PROGRAMMING

Exercise 3: (cont)
Write C++ program for each problem statements. Implement modular programming in your program.
Problem Statement 2: Conversion from Celsius to Fahrenheit. Write a program that able to print out a temperature conversion table form degrees in Celsius to degree in Fahrenheit when the temperature varies in the range of -10 to 40 degrees in Celsius with an incremental step size of 1 degree. The relationship is as follows:
f=(9/5)c+32

where c is the temperature in Celsius and f the temperature in Fahrenheit.

Sem II Session 2012/2013

31

MODULAR PROGRAMMING

Exercise 3: (cont)
Write C++ program for each problem statements. Implement modular programming in your program.
Problem Statement 3: Finding the highest score Write a program that prompts the user to enter the number of students and each students score, and displays the highest score. Problem Statement 4: Finding the highest and the lowest score Write a program that prompts the user to enter the number of students and each students score, and displays the highest and the lowest score.

Sem II Session 2012/2013

32

Das könnte Ihnen auch gefallen