{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# 08 - Lecture 8| Functions and Structured Programming...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lecture 8| Functions and Structured Programming Function Invocation Another Example Functions and Local Variables The return Statement Function with Single Parameter Function with Multiple Parameters Function Type Function with Return Value The return Statement | Summary Summary | Function De nition Function De nition Order Function Prototype Function Invocation and Call-by-Value Use of Random Numbers Another Example on Random Numbers Readings Exercises CSC 1500 { Lecture 8 1 Overview C functions are used to solve small problems. Small functions are combined into other larger functions and ultimately used in main(). CSC 1500 { Lecture 8 2 Function Invocation #include <stdio.h> prn_message() { printf("\tIn prn_message!\n") printf("\tHave a nice day!\n") } int main(void) { printf("In the main!\n") prn_message() printf("Back to main!\n") return 0 } In the main! In prn_message! Have a nice day! Back to main! A simple C function is a named block of statements. prn message() is a function. To invoke a function, { Write the function name followed by a pair of parentheses. { Program control passes to the function. { When the function reaches the closing brace ('g'), control is passed back to where it was called. CSC 1500 { Lecture 8 3 Another Example #include <stdio.h> prn_message() { printf("\tHave a nice day!\n") } int main(void) { printf("There is a message for you,\n") prn_message() prn_message() prn_message() return 0 } There is a message for you, Have a nice day! Have a nice day! Have a nice day! The same function can be called repeatedly, just like nothing has happened before. There is no data communication between the two functions prn message() and main() in this example. Function facilitates Code Re-use. CSC 1500 { Lecture 8 4 Functions and Local Variables #include <stdio.h> func() { int two two=2 printf("two is %d\n", two) } int main(void) { int one one = 1 func() return 0 } A function can have its own variables declared. Such variables are called local variables. They are also automatic variables. { Automatic construction upon entering a function. { Automatic destruction upon exiting a function. CSC 1500 { Lecture 8 5 Functions and Local Variables #include <stdio.h> func() { int (con't) two /* compilation error */ two = one } int main(void) { int one one = 1 func() return 0 } Local variables are only visible within the function in which they are declared. { one is visible only inside main(). { two is visible only inside func(). When the program is compiled, one will get an error message similar to the following: test.c: In function `func': test.c:8: `one' undeclared (first use in this function) The scope of a variable is the portion of the program that the variable is visible and thus accessible (the innermost pair of braces enclosing the variable). CSC 1500 { Lecture 8 6 Functions and Local Variables #include <stdio.h> func() { int local, x, y local = 2 y=3 x = local + y (con't) printf("\t x = %d\n", x) printf("\t local in func = %d\n", local) } int main(void) { int local local = 1 printf("local in main = %d\n", local) func() printf("local in main = %d\n", local) } local in main = 1 x=5 local in func = 2 local in main = 1 Di erent functions may have variables with the same name. But they are actually di erent variables with di erent scopes. CSC 1500 { Lecture 8 7 The return Statement #include <stdio.h> #include <math.h> func() { float do { printf("Number = ? ") scanf("%f", &num) if (num <= 0) return /* function termination */ else printf("SQRT(%.2f) = %.2f\n", num, sqrt(num)) } while (1) /* "forever" loop */ /* this line is never reached */ num } int main(void) { func() printf("\nThanks for using this program!\n") return 0 } c:\> run Number = ? 10 SQRT(10.00) = 3.16 Number = ? 81 SQRT(81.00) = 9.00 Number = ? 0 Thanks for using this program! c:\> CSC 1500 { Lecture 8 8 The return Statement (con't) When the return statement is reached, a function terminates immediately. A function may have more than one return statement. If there is no return, the function terminates when the execution reaches its closing brace (`g'). After function termination, program control is passed back to the caller. CSC 1500 { Lecture 8 9 Function with Single Parameter #include <stdio.h> prn_message(int k) { int i printf("Here is the message:\n") for (i = 0 i < k ++i) printf(" Have a nice day!\n") } int main(void) { int n printf("There is a message for you.\n") printf("How many times do you want to see it? ") scanf("%d", &n) prn_message(n) return 0 } There is a message for you. How many times do you want to see it? 3 Here is the message: Have a nice day! Have a nice day! Have a nice day! Function prn message() needs a single integer for performing its work. In the calling environment (i.e. main()), actual parameter (actual argument). n is used as an In function prn message(), formal parameter k receives the value of the actual parameter from the calling environment. CSC 1500 { Lecture 8 10 Function with Multiple Parameters #include <stdio.h> print_min(int x, int y) { if (x < y) printf ("min = %d\n", x) else printf ("min = %d\n", y) } int main(void) { int a, b printf("Input a? ") scanf("%d", &a) printf("Input b? ") scanf("%d", &b) print_min(a, b) return 0 } Input a? 80 Input b? 35 min = 35 Function print min() takes two integer parameters. In the calling environment (i.e. main()), variables a and b are used as arguments. In the function print min(), parameters x and y receive the values of the arguments from the calling environment. The type and number of parameters in the calling environment and in the function must be matched. CSC 1500 { Lecture 8 11 Function Type #include <stdio.h> void prn_message() { printf("\tHave a nice day!\n") } int main(void) { int n printf("There is a message for you,\n") prn_message() prn_message() prn_message() return 0 } Each function has a type, corresponding to the data value that it returns, if any. In ANSI C, if a function returns no value, its type should be void. We declare a function's type before its name. For example, void prn_message() { ... } Another example, int get_input() { ... } CSC 1500 { Lecture 8 12 Function with Return Value #include <stdio.h> int min(int a, int b) { if (a < b) return a else return b } int main(void) { int j, k, m printf("Input two integers: ") scanf("%d%d", &j, &k) m = min(j, k) printf("\nThe minimum is %d.\n\n", return 0 } m) Input two integers: The minimum is 3. 99 3 min() returns an integer. To return an integer value, the return statement is used. return expression where expression is the data value to be returned. Since min() returns an integer, its type is int. The return value of the function can be used by the calling environment (main() in the example). CSC 1500 { Lecture 8 13 The return Statement | Summary return return expression When a return is encountered, program control is passed back to where it was called. The rst form: { The rst return form is used when the function returns no value to the calling environment. { The type of the function must therefore be void. The second form: { The second form (return expression) is used when the function returns a value to the calling environment. { The value of the expression is returned. { The type of the expression must be the same as the type of the function. { The type of the function must therefore not be void. { Conversely, when the type of a function is not void, there must be at least one return expression statement with the correct expression data type. When there is no return statement in a function, control is passed back when the closing brace ('g') of the function is encountered. What type should this function be? CSC 1500 { Lecture 8 14 void fcn() { ... } void fcn() { ... return } Correct? void fcn() { ... return x } Correct? int fcn() { ... } Correct? int fcn() { ... return } Correct? int fcn() { int i ... return i } Correct? int fcn() { float f ... return f } Correct? int fcn() { int i float f ... if (...) return i else return f } Correct? CSC 1500 { Lecture 8 Correct? 15 Summary | Function Definition type function_name (parameter_type_list) { variable declarations statements return expression } /* end of the function */ /* end of the function */ The type of the function is the type of the value returned by the function. If there is no return value, type should be void. Without specifying a type indicates int implicitly (not encouraged to do so). is an identi er and is used when the function is to be called. There must be a pair of parentheses following the function name. function name The parameter type list describes the number and types of the (formal) parameters passed to the function when it's called. The (formal) parameters can be used inside the function just like variables. Both type and parameter type list can be void. CSC 1500 { Lecture 8 16 Function Definition Order #include <stdio.h> #include <stdlib.h> int sum(int a, int b) { ...... avg = average(x, y) ...... } float average(int a, int b) { ...... } void prn_value() { ...... } int main(void) { ...... } #include <stdio.h> #include <stdlib.h> float average(int a, int b) { ...... } int sum(int a, int b) { ...... avg = average(x, y) ...... } void prn_value() { ...... } int main(void) { ...... } Any problem with the order shown on the left? Solution is shown on the right. But what if, float average(int a, int b) { ...... total = sum(x, y) ...... } int sum(int a, int b) { ...... avg = average(x, y) ...... } CSC 1500 { Lecture 8 17 Function Definition Order #include <stdio.h> #include <stdlib.h> (con't) /* function prototypes/name cards */ int sum(int, int) float average(int, int) void prn_value() /* the functions thus may appear in any order */ int main(void) { ...... } int sum(int a, int b) { ...... } float average(int a, int b) { ...... } void prn_value() { ...... } CSC 1500 { Lecture 8 18 Function Prototype type function_name (parameter_type_list) Tells the compiler: { The number and type of parameters that are to be passed to the function. { The type of the value that is to be returned by the function. Parameter names (identi ers) can be omitted. int sum(int a, int b) is equivalent to int sum(int, int) Examples, float average(int, int) void prn_value() Don't miss the semicolon ( ) after a function prototype! Don't add a semicolon after a function de nition! CSC 1500 { Lecture 8 19 Function Invocation and Call-by-Value #include <stdio.h> int compute_sum (int) int main(void) { int n=3, sum printf("%d\n", n) sum = compute_sum(n) printf("%d\n", n) printf("%d\n", sum) return 0 } int compute_sum(int n) { int sum=0 for ( n>0 n--) sum += n printf("\t%d\n", n) return(sum) } 3 0 3 6 Arguments in a function invocation are evaluated rst. Their values are copied to the called function's parameters. When the value of a formal parameter in the called function is changed, the calling function will not be a ected. Thus, the arguments and the formal parameters can use identical variable names. CSC 1500 { Lecture 8 20 Use of Random Numbers #include <stdio.h> #include <stdlib.h> int main(void) { int i for (i=0 i<10 i++) printf("%d\n", rand()) return 0 } 16838 5758 10113 17515 31051 5627 23010 7419 16212 4086 16838 5758 10113 17515 31051 5627 23010 7419 16212 4086 CSC 1500 { Lecture 8 21 Use of Random Numbers #include <stdio.h> #include <stdlib.h> int main(void) { int i, seed printf("Seed = ? ") scanf("%d", &seed) srand(seed) (con't) for (i=0 i<5 i++) printf("%d\n", rand()) return 0 } C:\program> random.exe Seed = ? 5 18655 8457 10616 31877 10193 C:\program> random.exe Seed = ? 10 4543 28214 11245 8870 16887 CSC 1500 { Lecture 8 22 Another Example on Random Numbers #include <stdio.h> #include <stdlib.h> #include <time.h> void prn_random (int k) int main (void) { int n printf("How many random coordinates? ") scanf("%d", &n) prn_random(n) return(0) } void prn_random(int k) { int i, seed seed=time(NULL) srand(seed) for (i=1 i<=k i++) printf("%.2f %.2f\n", (float)rand()/RAND_MAX, (float)rand()/RAND_MAX) } How many random coordinates? 10 0.51 0.18 0.31 0.53 0.95 0.17 0.70 0.23 0.49 0.12 0.08 0.39 0.28 0.37 0.98 0.54 0.77 0.65 0.77 0.78 CSC 1500 { Lecture 8 23 Another Example on Random Numbers (con't) 1000 1 "out" 0.8 0.6 0.4 0.2 0 0 0.2 0.4 0.6 0.8 1 10000 1 "out" 0.8 0.6 0.4 0.2 0 0 0.2 0.4 0.6 0.8 1 CSC 1500 { Lecture 8 24 Readings Chapter 4, Sections 4.1 { 4.5 Chapter 4, Sections 4.8 { 4.9 Chapter 4, Sections 4.12 Chapter 4, Sections 4.14 { 4.16 Exercises Chapter 4, Exercises 2, 6, 7, 9, 10, 12, 16 2 End of Lecture 8 CSC 1500 { Lecture 8 25 ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online