Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016.

Similar presentations


Presentation on theme: "Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016."— Presentation transcript:

1 Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016

2 Source: xkcd.com/1742

3 Announcements Homework #3 due up front Homework #4 due in two weeks  (functions and midterm review) Midterm – two weeks  Open book  Open notes

4 Learning Objectives Explain the concept of modular program design Explain the concept of a function in C Explain why functions are important in programming Explain the structure of a function  Return data type  Parameters Apply the concept of a function to a practical problem

5 Modular Programming Break a large problem into smaller pieces  Smaller pieces sometimes called ‘modules’ or ‘subroutines’ or ‘procedures’ or functions  Why? Helps manage complexity  Smaller blocks of code  Easier to read Encourages re-use of code  Within a particular program or across different programs Allows independent development of code Provides a layer of ‘abstraction’ a = sqrt(9.0);

6 Functions The ‘building blocks’ of a C program  You’ve used predefined functions already: main() printf(), scanf(), pow()  User-defined functions Your own code In combination with predefined functions

7 Functions - Mathematical View X Function Returned value

8 Functions - Definition Structure Function 'header'  Return data type (if any)  Name Descriptive  Arguments (or parameter list) Notice: data type and name Statements  Variable declaration  Operations  Return value (if any) type function_name (type arg1, type arg2 ) { statements; } double product(double x, double y) { double result; result = x * y; return result; } A function that calculates the product of two numbers

9 Functions - Example Function prototype  Like a variable declaration Tells compiler that the function will be defined later Helps detect program errors Note semicolon!! Function definition  See previous slide  Note, NO semicolon Function return  return statement terminates execution of the current function  Control returns to the calling function  if return expression; then value of expression is returned as the value of the function call Only one value can be returned this way Function call  main() is the 'calling function'  product() is the 'called function'  Control transferred to the function code  Code in function definition is executed #include /* function prototype */ double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }

10 Function - Practice 1 Write a function named 'sum'  sums two integers  returns the sum 2 min. on your own Share with neighbor Steps 1.Function header return data type function name argument list with data types 2.Statements in function definition variable declaration operations return value

11 Function - sum() int sum_int(int x, int y) { int result; result = x + y; return result; }

12 Recall: Examples float b = 17.0; float d = 3.14; float c = 20.0; float e = 33.0; (b < c); //true (b + c); //true (not zero) ((int)(b/c)); //false (is zero, why?) (b e); //false (b e); // true (b e) || (c < e); //true (b e) || (b + c); //true, why? printf(“%f”, b) && (b + c); //true, why?

13 Using Functions – an Example #include float sum( float a, float b ); // Note that one can use a function // which returns a float in any place int main( void ) // where one can use a float { float a = 34, b = 67; float c = sum(a, b); // ex: in an initialization/assignment float d = sum( sum(a, b), c ); // ex: within another function call float e = sum(a, b) + sum(c, d); // ex: in an expression printf("The sum of %f and %f is %f\n", a, c, sum(a, c) ); printf("The sum of %f, %f, and %f is %f\n", a, b, c, d); return 0; } float sum( float x, float y ) { return (x + y); }

14 Passing Arguments into Functions (By Value) How are the arguments passed into functions?  'Pass by value‘  function arguments are expressions  In the function call: Expressions are evaluated and copies of their values are put into temporary memory locations The names of the corresponding parameters in the function definition are made to be the names of the copies  The values of the expressions in the function call are not changed #include double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans = 0; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0; } /* function definition */ double product(double A, double B) { double result = 0; result = A * B; return result; }

15 Passing Arguments into Functions (By Value) How are the arguments passed into functions?  'Pass by value‘  function arguments are expressions  In the function call: Expressions are evaluated and copies of their values are put into temporary memory locations The names of the corresponding parameters in the function definition are made to be the names of the copies  The values of the expressions in the function call are not changed #include double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans = 0; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0; } /* function definition */ double product(double A, double B) { double result = 0; result = A * B; return result; }

16 Functions Returning Multiple Values (Pass by Reference) Instead of sum()  prod_sum()  How can I get both product and sum returned? put * in front of variable name in prototype and function definition put & in front of variable names in function call #include void prod_sum(double x, double y, double *ptr1, double *ptr2); int main() { double var1 = 3.0, var2 = 5.0; double prod = 0, sum = 0; prod_sum(var1, var2, &prod, &sum); printf("var1= %g\n" "var2= %g\n",var1, var2); printf("prod= %g\n" "sum= %g\n", prod, sum); } /* function definition */ void prod_sum(double A, double B, double *rslt_prod, double *rslt_sum) { *rslt_prod = A * B; *rslt_sum = A + B; }

17 Returning Multiple Values - Practice 2 Write a function that returns the square and cube of a number  Prompts user for the number  Prints number, square, and cube  Prompt, square- cube calculation, and print must all be functions Steps 1.Pseudocode for program logic The actions that your program will do Everyone individually 2 minutes 2.Form into groups of three Share pseudocode (3 minutes) Divide up task to build functions 3.Write code

18 Function – sq_cube() #include void sq_cube( float n, float *square, float *cube ); // note the *s // note the return type. int main( void ) { float a = 45, s = 67, c = 67; sq_cube( a, &s, &c ); // note the &s printf("The square of %f is %f and cube is %f\n", a, s, c); return 0; } void sq_cube( float n, float *square, float *cube ) { *square = n * n; *cube = n * n * n; }

19 Recall: what is an array? int nums [10];  10 element array of integers Element no. 3 is accessed by: nums [2] because indexing begins at 0

20 Passing an Array to a Function Prototype and function header need:  data type  array name  [ ] Function call with actual name of the array Note: in the function prototype and function header char *array would also work (i.e. arrays are always passed by reference) #include void PrintArray(int elements, char array[]); int main() { /* initialize the array */ char test[]={'M','E','3','0'}; /* get the size of the array */ int num_elem=sizeof(test)/sizeof(char); /* pass array to function */ PrintArray(num_elem, test); return 0; } /* PrintArray() function definition */ void PrintArray(int num_elem, char array[]) { int i=0; for(i=0; i<num_elem; i++) { printf("test[%d]==%c",i,array[i]); printf(" @ 0x%p\n",&array[i]); }

21 Scope of Identifiers Scope of a declaration of an identifier  The region of the program that the declaration is active (i.e., can access the variable, function, label, etc.) Five types of scope:  Program (global scope)  File  Function prototype  Function  Block (“between the { } scope”)

22 Scope of Identifiers - Block Scope Block (local) scope  A block is a series of statements enclosed in braces { }  The identifier scope is active from the point of declaration to the end of the block ( } )  Nested blocks can both declare the same variable name and not interfere #include double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans = 0; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }

23 References Modular Programming in C http://www.icosaedro.it/c-modules.html http://www.icosaedro.it/c-modules.html math.h http://www.opengroup.org/onlinepubs/007 908799/xsh/math.h.html http://www.opengroup.org/onlinepubs/007 908799/xsh/math.h.html http://www.cprogramming.com/tutorial/styl e.html http://www.cprogramming.com/tutorial/styl e.html


Download ppt "Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016."

Similar presentations


Ads by Google