








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









Introduction Modularity is an important part of the algorithm/program design process. Most algorithms solve complicated problems that are best understood and solved in pieces. Modularity allows the designer to abstract the various pieces needed to solve the problem into manageable size tasks. Modularity ļ· Subalgorithms are used to simplify the algorithm design and understanding. ļ· This is not just a āavailable optionā, but the core of good algorithm design. ļ· Algorithms that do not feature modularity are low abstraction, hard to understand, and hard to debug. ļ· Modularity must be incorporated into any well designed algorithm. A Hierarchy of Abstraction ļ· Each subalgorithm handles a single logical āchunkā of the solution. ļ· The āmainā algorithm coordinates the overriding logic. Graphical representation of abstraction featuring modularity ļ· It is abstraction because we are āconsidering the essenceā (each task) āapart from the embodimentā (its component parts). Modularity: Functions - (^1)
Main algorithm Task 1 Task 2 Task Sub-task^3
Sub-task
ļ· It is a hierarchy of abstraction because weāre doing this at multiple levels: main, tasks, sub-tasks, sub-tasks of sub-tasks, etc. The details are hidden in the tasks and sub-tasks. Advantages of Modularity ļ· The details of the algorithm are hidden in the subalgorithms. This enhances understanding the algorithms by hiding obscure details. ļ· Makes the algorithm easier to write by reducing the complexity. ļ· Saves time, space, and effort. Modules can be called from many different places within an algorithm. Rather than repeating the task, you simply call the same task again. Sort of like speed-dial on your phone. ļ· Permits the reuse of logic. If properly designed, modules can be reused across different algorithms. All that is required is that the different algorithms need the same sub-task to be performed. ļ· Enhances the ability to maintain and reuse the implemented algorithm. Module Interfaces ļ· An interface is the common boundary between two bodies or spaces. In algorithmic terms, the interface specifies how the module can be connected to the outside world (i.e., to other algorithms). Example Consider the problem of obtaining a list of names, sorting those names into alphabetical order, and finally printing out the sorted list of names. This problem can logically be broken into three separate tasks (modules); (1) An input module to read the list of names. (2) A module to sort the names. (3) An output module to print the sorted list of names. When considering the second module to sort the names, we can choose any sorting technique that we want and change it whenever we feel like it without affecting the rest of the algorithm. One thing will remain constant throughout our changing of the sorting technique in the second module and this will be how the module interfaces with the outside world. In Modularity: Functions - (^2)
ļ· Functions that return a value ā functions that perform some subtask that requires returning some value to the calling function. ļ· Void functions ā functions that perform some subtask that does not require a single value to be returned to the calling function. To incorporated the modularity provided by functions in C programs you need to be able to do two things:
C Library Functions Shown below are a few of the functions available in some of the various C libraries that you will find useful. Library: ctype.h int isalpha (int c); int isdigit (int c); int isupper (int c); int islower (int c); int tolower (int c); int toupper (int c); Library: math.h double cos (double x); double acos (double x); double cosh (double x); double exp (double x); double ceil (double x); double floor (double x); double fabs (double x); double pow (double x, double y); double sqrt (double x); Library stlib.h int rand(void); void srand (unsigned seed); General Structure of a C Program ļ· A program is constructed of one or more functions; one of which must be main( ). Modularity: Functions - (^5)
Function Headings A function heading must match up with a corresponding function declaration (prototype). The return type and a function name must be the same in the heading as they are in the declaration, and the arguments must match in a one- to-one correspondence between type and position. In addition, each type in the argument list of a function heading must be followed by an argument name, usually called a formal parameter. The formal parameter list must match the number of arguments (usually called actual parameters ) used when the function is called. The general form of a function heading is: < return type> < function name > (< list of formal parameters >) Data and Executable Statements in a Function Implementation ļ· Declaration section is optional. ļ· The executable statement section has the same form as the executable statement section of the main function. ļ· Unless it is a void function, a function implementation must include at least one statement of the form: return < expression > Parameter Lists In the function heading: int min (int num1, int num2, int num3) Modularity: Functions - (^7)
In the call to the module: int smallest; smallest = min (a, b, c); Rules for Parameter Lists ļ· The number of parameters in the actual and formal parameter lists must be consistent. ļ· Parameter association in C is positional. This means that the first actual parameter corresponds to the first formal parameter, the second matches the second and so on. ļ· Actual parameters and formal parameters must be of compatible data types. ļ· Actual (input) parameters may be a variable, constant, or any expression matching the type of the corresponding formal parameter. For example, using the previous example we could have: smallest = min(15, a, 5*b); Examples Example 1 Function implementation: Modularity: Functions - (^8) The formal parameter list. (parameter variables and their types are declared here) The actual parameter list. (cannot tell the parameter type from here) //Function: min //Finds the minimum of three integer values // //Input: three integer values //Output: The integer which is the smallest in the list. int min (int num1, int num2, int num3) { int minimum; local declaration if (num1 < num minimum = num1; else executable statements minimum = num2; if (num3 < minimum) minimum = num3; return minimum; returned value }
Example 3 Modularity: Functions - (^10) //Function: compute_grade //Returns a numerical value between 0 and 4 corresponding to a given letter // grade. If the grade is invalid a ā1 will be returned. // //Input: A single character. The character must be one of the following: // āAā, āBā, āCā, āDā, or āFā. //Output: A numerical value. A= 4, B = 3, C = 2, D = 1, and F = 0. int compute_grade (char grade) { if (grade == āAā) return 4; else if (grade == āBā) return 3; else if (grade == āCā) return 2; else if (grade == āDā) return 2; else if (grade == āFā) return 1; else return ā1; }//end compute_grade
Example 4 Modularity: Functions - (^11) //This program conducts a shopping spree and prints the total amount spent #include <stdio.h> double total_with_tax(double value, double tax_rate); int main ( ) { char ans; double total_spent = 0.0; price, tax_rate; printf (āIs there another item to buy?\nā); scanf(ā%cā, &ans); while (ans == āyā) { //read in value of item and tax_rate printf (āEnter the item price and tax_rate.\nā); scanf (ā%lf%lfā, &price, &tax_rate); //reset the total total_spent = total_spent + total_with_tax(price, tax_rate); printf (āIs there another item to buy?\nā); scanf(ā%cā, ans); } printf (āYou spent %lf on your shopping spree.\nā, total_spent); return 0; } //end main //Function: total_with_tax //Input: value is a positive number and tax_rate is between 0 and 1. //Output: This function returns the total cost of an item based upon its price // and the tax_rate. double total_with_tax (double value, double tax_rate) { return value * (1 + tax_rate); } //end total_with_tax
Void Functions A void function does not return a value to the calling algorithm. A return statement is not included in a void function. After the last statement in a void function is executed, the control of execution is returned to the calling point in the calling algorithm (function). Modularity: Functions - (^13) #include <stdio.h> int triangle_num (int n); int main ( ) { int index; //print first 20 triangle numbers for (index = 1; index <= 20; index++) printf (ā%d triangle number is %d\n, index, triangle_num(index)); }//end main //Function: triangle_num //Computes the sum of the first n integer numbers //Input: n is a positive integer //Output: The sum of 1 + 2 + 3 + ⦠+ n int triangle_num (int n) int index = 1, sum = 0; //return 0 if input is invalid if (n < 1) return 0; //compute sum for (index = 1, index <= n; index++) sum += index; return sum; }//end function triangle_num
Creating a void function void function_name (formal parameters) { . . . } Example Modularity: Functions - (^14) void draw_a_square (int length) { int i, j; for (i = 1; i <= length; i++) { for (j = 1; j <= length; j++) printf (ā*ā); printf (ā\n|); } }//end function