Modular Programming with Functions B Ramamurthy Chapter 5
Modular Programming with Functions B. Ramamurthy Chapter 5 1 1/5/2022 BR
Introduction l l l 2 Complex problems: Divide and conquer Reusability of code Modular design of software to enhance readability and maintenance. Abstraction Information hiding 1/5/2022 BR
Libraries of Functions l l l 3 We have used functions from many libraries: cmath : pow, sin, cos fstream : open, close, get, set iomanip: setw, setprecision iostream : << , >> Programmers can define functions for use in their program: programmer-defined functions. 1/5/2022 BR
Functions Definition 1. 2. 3. 4. l Function header Function parameters Function body Function return value In fact int main() { … return 0; } is a function. 4 1/5/2022 BR
Function syntax type functio. Name (parameters) { declare local variables/constants statements } 5 1/5/2022 BR
Example int factorial (int n) { int prod; for (int i = 1; i <= n; i++) prod = prod *i; return prod; } 6 1/5/2022 BR
Structure Charts l l Structure charts are often used to represent the modular design. Here is an example of a structure chart for Stick. Figure. main draw. Triangle 8 draw. Hollow. Rectangle 1/5/2022 draw. Rectangle BR
Part of Stick Figure * ************** * * * ***** 9 Step 1 : Draw triangle Step 2: Draw rectangle Step 3: Draw hollow rectangle 1/5/2022 BR
draw. Triangle(. . ) for (int i 3 = 0; i 3 < row; i 3++) { for (int k = 1; k<= offset; k++) cout<< ' '; for (int j = 1; j <= col; j++ ) cout <<'*'; offset = offset -1; col = col +2; cout<< endl; } 10 1/5/2022 BR
draw. Rectangle(. . ) for (int i 4 = 1; i 4 <= length; i 4++) { for (int k = 1; k<= offset; k++) cout<< ' '; for (int j = 1; j<= width; j++) cout <<'*'; cout<< endl; } 11 1/5/2022 BR
draw. Hollow. Rectangle(. . ) 12 for (int i 4 = 1; i 4 <= length; i 4++) { for (int k = 1; k<= offset; k++) cout<< ' '; if ((i 4 ==1 ) || (i 4 == length)) { for (int j = 1; j<= width; j++) cout <<'*'; } else { cout << '*'; for (int k =1; k<= width-2; k++) cout << ‘ '; cout << '*'; } cout<< endl; } 1/5/2022 BR
- Slides: 12