Functions - Comp Sci
Structured Programming
Definition: Structured/modular programming is the process of subdividing a computer program into separate sub-programs, functions, or modules.
Modules: A part of a program that carries out a particular task.
Control Structures
Used in structured programming:
Sequence: Execution of statements one after another.
Selection: Decision-making statements (e.g. if, switch).
Iteration: Looping through statements (e.g. for, while).
Prohibited: The use of the GO TO statement is not allowed.
Advantages of Structured Programming
Manageability: Makes problem solutions more manageable.
Ease of Testing and Debugging: Individual segments are easier to test rather than the entire solution.
Logical Simplification: Simplifies logical steps of each sub-problem, and by extension, the entire solution.
Maintenance: Eases program maintenance due to clear modular design.
Reusability: Modules can be kept in a library for reuse in other programs.
Team Collaboration: Enables several programmers to work on separate modules, reducing development time for large projects.
Reduced Code: Less code must be written due to the reuse of functions.
Error Localization: Errors can be easily identified as they are encapsulated within specific functions.
Variable Scope Control: Easier control of variable scope through modular design.
Design Approaches
Top-Down Design / Stepwise Refinement / Decomposition
Description: This process involves breaking a problem into its major tasks. Each task is subdivided into subtasks repeatedly until each is simple enough to be coded as a module or function.
Main Use: Primarily applied in structured programming languages like C, COBOL, and FORTRAN.
Advantages
Problem Breakdown: Aids in identifying tasks that need to be completed.
Complexity Decrease: Each step of refinement results in a decrease in complexity, making problems easier to solve.
Reusability Potential: Identified parts of the solution may be reusable in other contexts.
Collaborative Problem Solving: Allows multiple individuals to work simultaneously on different parts of the problem.
Efficient Testing and Debugging: Simplifies the testing and debugging process.
Disadvantages
Changing Specifications: Project specifications may evolve over time; decisions made early can depend on high-level abstractions that may change.
Example: ATM Software Modules
Display Balance Module
Deposit Funds Module
Transfer Funds Module
Withdraw Funds Module
May be subdivided into mini-modules:
Get Available Balance
Compare Available Balance to Requested Amount
Disburse Funds or Reject Request
Update Customer's Account
Print Receipt
Bottom-Up Design
Description: Initiates with designing algorithms at the basic level and builds up the complete solution through the integration of these individual parts.
E.g., Writing routines to fetch a single byte from a communication port before integrating them into a full communication program.
Main Use: Commonly used in object-oriented programming (e.g., C++, C#, Python, Java, Perl).
Advantages
Test Condition Creation: Easier to create test conditions for individual components.
Observation of Results: Easier analysis of the results of tests conducted on individual components.
Data Encapsulation: Reduces redundancy due to data encapsulation principles.
Code Reusability: Promotes the reuse of previously developed code.
Disadvantages
Solving Unneeded Problems: May require solving sub-problems that are ultimately unnecessary, leading to additional computations.
Functionality Recognition: It can often be challenging in the initial stages to identify the overall functionality of the entire system.
Comparison of Design Approaches
Aspect | Top-Down Design | Bottom-Up Design |
|---|---|---|
Focus | Breaking up problems into smaller parts. | Solving smaller problems and integrating them into a whole. |
Languages | Mainly used by structured programming languages (e.g., Pascal, Fortran, C) | Mainly used by object-oriented programming languages (e.g., C++, C#, Python) |
Process | Decomposition | Composition |
Functions
Definition: A function (or subroutine) is a code block that performs a specific task within a larger program.
Function Prototypes
Definition: Prototypes inform the compiler how a function is built and what parameters it will receive.
Void Usage:
If placed in the parameter list suggests no parameters are accepted.
If placed before a function name, indicates no return value.
Format and Example
Format:
Example:
The left
intindicates the function returns an integer value, while the parameters specify it expects two integer inputs.
Function Definitions
Definition: Provides the actual implementation of the function.
Format:
Example:
The
returnkeyword passes a value back to whoever called the function.
Calling Functions
Usage: To invoke a function, use its name along with the necessary arguments.
Example:
Example Code Snippet in C
#include <stdio.h>
#include <conio.h>
// Function Prototype
int area(int, int);
// Function Definition
int area(int length, int width) { // This function returns the area
return length * width;
}
int main() {
int len, wid; // Declare variables
// Prompt user to enter length and width
printf("Enter the length and width \n");
scanf("%d%d", &len, &wid);
printf("The area is %d", area(len, wid)); // Call function
getch();
}
Documentation Example for C Program Using Area Function
Module: Area
Narrative: This module accepts two integer parameters, length and width, returning the product of the two.
Pseudocode:
Function Area(length, width)
Begin
// This function returns the area
Return length * width
End
Data Dictionary:
Variable Name
Data Type
Purpose
length
int
Holds the length of an object.
width
int
Holds the width of an object.
Module: Main
Narrative: Prompts the user for length and width, storing in len and wid variables, and calls the area function.
Pseudocode:
Function Main () Begin // This function calls area function and displays area Print "Enter the length and width" Read len, wid Print "The area is ", area(len, wid) EndData Dictionary:
Variable Name
Data Type
Purpose
len
int
Holds the length of an object.
wid
int
Holds the width of an object.
Programming Tasks
Task Examples
Write a C function that converts Celsius to Fahrenheit.
Function Prototype:
float celsiusToFahrenheit(float celsius);
Function Definition:
float celsiusToFahrenheit(float celsius) { return (celsius * 9/5) + 32; }
Write a C program that reads mass and calculates weight using the force function.
Weight Formula:
Weight = mass * 10.
Write a C program that reads ten numbers into an array and counts the even numbers.
Write a C program that reads a student's first name and counts its characters.
Write a C program that reads item costs from a file and calculates VAT (17.5%).
Differences Between Top-Down and Bottom-Up Design
Focus: Top-down emphasizes breaking down problems, while bottom-up focuses on building up from basic elements.
Integration: Top-down integrates solutions built from high-level tasks; bottom-up integrates components designed as individual elements.
Documentation and Design Tasks
Write documentation for the program from question 2.
For the problem of calculating the average score of 20 students, utilize top-down design to partition the problem into subtasks.
Create a diagram representing the tasks from question 8.