Modular Programming with Functions B. Ramamurthy Chapter 7 12/5/2018 BR
Introduction Complex problems: Divide and conquer Reusability of code Modular design of software to enhance readability and maintenance. Abstraction Information hiding 12/5/2018 BR
Libraries of Functions 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. 12/5/2018 BR
Functions Definition Function header Function parameters Function body Function return value In fact main() is a function. int main() { … return 0; } 12/5/2018 BR
Function syntax type functioName (parameters) { declare local variables/constants statements } 12/5/2018 BR
Example int factorial (int n) { int prod =1; for (int i = 1; i <= n; i++) prod = prod *i; return prod; } 12/5/2018 BR
Example: drawRectangle ********* 12/5/2018 BR
Draw a small rectangle *** 12/5/2018 BR
Draw a large rectangle ********************** 12/5/2018 BR
drawRectangle(..) for (int i4 = 1; i4 <= length; i4++) { for (int k = 1; k<= offset; k++) cout<< ' '; for (int j = 1; j<= width; j++) cout <<'*'; cout<< endl; } 12/5/2018 BR
Function Parameters Write a function for rectangle code Parameterize the function: add length and width as parameters to the function Call/Invoke function with different parameters. 12/5/2018 BR
Summary Functions provide basic construct to modularize you solution. Practice writing functions. Read Chapter 7. 12/5/2018 BR