Docsity

Understanding Modularity and Functions in C Programming, Study notes of Computer Science

Toggle sidebar
bg1
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
Modularity: Functions – Chapter 7
Main algorithm
Task
1
Task
2
Task
3
Sub-task
2.1
Sub-task
2.2
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Understanding Modularity and Functions in C Programming and more Study notes Computer Science in PDF only on Docsity!

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)

Modularity: Functions – Chapter 7

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:

  1. Create functions.
  2. Call functions from the main function as well as other functions. Function Declarations A function’s declaration ( prototype ) gives us all the information that we need to know about how to use the functions and no other details are provided. For example: double power (double base, double exponent); This prototype tells us that the function is named power and it returns a type double and has two parameters both of which are of type double. The general format of a function declaration in C is: return-type function_name ( list of argument specifiers ) where: return-type – specifies the type returned by the function. function_name – any identifier you appropriately choose. argument specifiers – list of type-identifier pairs, showing the number of parameters with their types. No information about how the function performs its task is provided, however, the user has enough information to invoke or use the function. Examples Modularity: Functions - (^4) int f (char c, int i); //note: parameter names need not be declared in the //prototype. See next example. double find_avg (int, int);

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