Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.

Similar presentations


Presentation on theme: "Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05."— Presentation transcript:

1 Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05

2 Homework, etc. Read Chapter 5 Read Chapter 5 HW4 HW4 The project will be posted next week. Details to follow… The project will be posted next week. Details to follow…

3 Functions Recall that a C program is a collection of functions. Recall that a C program is a collection of functions. every C program must have a function called main every C program must have a function called main program execution always begins with function main program execution always begins with function main any other functions are subprograms and must be called any other functions are subprograms and must be called

4 More About Functions it is not considered good practice for the body block of function main to be long it is not considered good practice for the body block of function main to be long function calls are used to do tasks function calls are used to do tasks every C function has a return type every C function has a return type (main returns int) if the return type is not void, the function returns a value to the calling block if the return type is not void, the function returns a value to the calling block

5 Where are functions? located in libraries located in libraries Ex: The square root function is in the math.h library - need to #include to use it. Ex: The square root function is in the math.h library - need to #include to use it. discriminant = sqrt ( b * b – 4 * a * c); OR written by programmers written by programmers

6 HEADER FUNCTION EXAMPLERESULT FILE OF CALL HEADER FUNCTION EXAMPLERESULT FILE OF CALL sqrt(float x)s = sqrt(100.0);s = 10.0 sqrt(int x)t = sqrt(2);t = 1.41421 sin(float x)a = sin(3.0);a = 0.14112 log(float x)c = log(2.0);c = 0.30102 printf(…) printf(“Hello, World”); Hello, World scanf(…) scanf(“%d”, &number); number = input abs(int i)a = abs(-6);a = 6

7 Two Kinds of Functions Always returns a single value to its caller and is called from within an expression. Never returns a value to its caller, and is called as a separate statement. Value-Returning Void Value-Returning Void 7

8 int num1; int num2; int highest; printf(“Enter two numbers: ”); scanf(“%d%d”, &num1, &num2); highest = findHighestNum( num1, num2 ); printf(“Printing something to the screen…”); mysteryFunction( num1, num2 ); void function example value- returning function example

9 Any user-defined function consists of 3 parts: Function declaration (a.k.a. prototype) Function declaration (a.k.a. prototype) Tells the compiler you will be defining this function later. The declaration must come before main. Tells the compiler you will be defining this function later. The declaration must come before main. Same as the header but has a semicolon (;) after it Same as the header but has a semicolon (;) after it Function definition Function definition Heading = return type, function name, parameter list Heading = return type, function name, parameter list Body = actual code Body = actual code Function call Function call Using the function Using the function

10 What is in a heading? int main ( ) { return 0; } 10 type of returned value name of function says no parameters

11 Every C function has 2 parts int main ( ) { stmt_1; … stmt_n; return 0; } 11 heading body block

12 Function Calls 1. one function calls another by using the name of the called function together with ( ) containing an argument list 2. a function call temporarily transfers control from the calling function to the called function 3. when the function’s code has finished executing, control is transferred back to the calling block

13 Trace of a Function Call int main ( ) { int num1, num2, highest; printf(“Enter two numbers: ”); scanf(“%d%d”, &num1, &num2); highest = findHighestNum(num1, num2); printf(“\nThe highest number is %d.\n”, highest); return 0; }

14 Functions that return values Sometimes a function computes a value needed by the rest of the program Sometimes a function computes a value needed by the rest of the program Functions must be able to return computed values before they terminate. Functions must be able to return computed values before they terminate. the sqrt function does this the sqrt function does this If a function’s return type is anything other than void, then we usually use the function call in an expression If a function’s return type is anything other than void, then we usually use the function call in an expression Examples: Examples: x = y + sqrt(20); c = max(a, b);

15 Program with Two Functions main function square function

16 Function Definition int Square ( int n ) header { int sq = n * n; body return sq; } Return Function Parameter Parameter Type Name

17 Using the Square function #include int Square (int n); /* declare function */ int main( ) { int x, sq; printf("Enter a number: “); scanf(“%d”, &x); sq = Square( x ) ; /* function call */ printf(“The square of %d is %d\n”, x, sq); printf(“Goodbye\n”); return 0 ; }

18 Rest of the program /* Define function */ int Square ( int n ) { int s; int s; s = n * n; s = n * n; return s; }

19 Output of the Program Enter a number: 15 The square of 15 is 225 Goodbye

20 Functions that return values If a function returns a value, the last statement executed must be a return statement. If a function returns a value, the last statement executed must be a return statement. Syntax: return ; Syntax: return ; After a return statement is executed no other statements in the body of the function are executed After a return statement is executed no other statements in the body of the function are executed Equivalent to: int max (int x, int y) { int myMax; if (x > y) myMax = x; else myMax = y; return myMax; } int max (int x, int y) { if (x > y) return x; return y; }

21 To call the max function int a, b, c; printf(“Enter two values:”); scanf(“%d %d”, &a, &b); c = max(a, b); printf(“The max is %d”, c);

22 Trace of a Function Call int main ( ) { int num1, num2, highest; printf(“Enter two numbers: ”); scanf(“%d%d”, &num1, &num2); highest = findHighestNum(num1, num2); printf(“\nThe highest number is %d.\n”, highest); return 0; } int findHighestNum( int num1, int num2) { if(num1 > num2) return num1; else return num2; }

23 void functions Functions which do not return a value are called void functions. Use void as the return type. Functions which do not return a value are called void functions. Use void as the return type. void functions are usually used to go off and “do something,” but they do NOT return a value. void functions are usually used to go off and “do something,” but they do NOT return a value. The most common use of a void function is to print something. The most common use of a void function is to print something.

24 void FunctionName ( Argument List ); The argument list is a way for functions to communicate with each other by passing information. The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function. Syntax To Call a void Function

25 Example of a void function /* Definition */ void printDay(int num) { if (num == 0) printf(“Sunday”); else if (num == 1) printf(“Monday”); else if (num == 2) printf(“Tuesday”);… else if (num == 6) printf(“Saturday”);else printf(“Invalid day”); } #include /* declaration */ void printDay(int num); int main( ) { int day; printf(“Enter a number between 0 and 6”); scanf(“%d”, &day); /* Call */ printDay(day); return 0; }

26 Example of a void function /* Definition */ void printDay(int num) { switch(num) { case 0: printf(“Sunday”);break; case 1: printf(“Monday”);break;… case 7: printf(“Sunday”);break;default: printf(“Invalid day”); }} #include /* declaration */ void printDay(int num); int main( ) { int day; printf(“Enter a number between 0 and 6”); scanf(“%d”, &day); /* Call */ printDay(day); return 0; }

27 Parameter List is the means used for a function to share information with the block containing the call is the means used for a function to share information with the block containing the call use commas to separate multiple parameters use commas to separate multiple parameters each parameter needs a type and name each parameter needs a type and name

28 Classified by Location Always appear in a function call within the calling block. Always appear in the function heading, or function prototype. Arguments Parameters Arguments Parameters a.k.a. “Actual Parameters” a.k.a. “Formal Parameters”

29 Example – What’s the output? #include #include void fun (int b, int c, int a); int main() { int a = 1, b = 3, c = 5; fun(a, b, c); fun(a, b, c); return 0; Arguments } Parameters void fun (int x, int y, int z) { printf(" %d %d %d”, x, y, z); } Output 1 3 5

30 Example – What’s the output? #include #include void fun (int b, int c, int a); int main() { int a = 1, b = 3, c = 5; fun(a, b, c); fun(a, b, c); return 0; Arguments } Parameters void fun (int a, int b, int c) { printf(" %d %d %d”, a, b, c); } Output 1 3 5 As long as the variable names are consistent throughout the function you can name them anything. They are local to the function and will not change the variables outside the function, even if they have the same names.

31 Variable Rules C uses pass by value to pass values to functions. This means that when a function is called, the values in the arguments (in the function call) are copied to the values in the parameters (in the function definition) C uses pass by value to pass values to functions. This means that when a function is called, the values in the arguments (in the function call) are copied to the values in the parameters (in the function definition) Any variable declared inside a function can only be used in that function. These are called local variables, I.e. they are local to the function. Any variable declared inside a function can only be used in that function. These are called local variables, I.e. they are local to the function. Parameters are also treated as local variables Parameters are also treated as local variables

32 Global variables Any variable declared at the beginning of the program outside of all functions is called a global variable. It can be “seen” and changed by any function. #include int x; void fun(int n); int main( ) { int a = 5; x = 10; printf(“%d %d\n”, a, x); fun(a); printf(“%d %d\n”, a, x); return 0; } void fun(int n) { x = 20; n = 30; } 5 10 5 20 Output

33 Boolean functions Recall that boolean values are either 0 or 1. Therefore a boolean function is one that returns either 0 or 1. /* Return 1 if n is prime, 0 if n is not prime */ int isPrime(int n) {…} /* Call - Prints out i if it is prime */ if (isPrime(i)) printf(“%d”, i);

34 Things to Note In a function call, you do not include the data type of the variable. In a function call, you do not include the data type of the variable. Right: c = min(a, b); Wrong:c = min (int a, int b); If a function returns a value, you must call it in an assignment statement or in a condition in order to use the return value. If a function returns a value, you must call it in an assignment statement or in a condition in order to use the return value. Right:c = min(a, b); if (isPrime(n)) Wrong:min(a, b); isPrime(n);

35 The Lab You can take the rest of class time to work on the lab. (Do not use the math.h library for these exercises). Note: For HW4, if you would like you may use some of the math functions (in the math.h library) mentioned in this lecture or in Chapter 5. You will then need to compile your program differently: gcc –lm exercise4.c where –lm stands for (“L”ink to “M”ath library)


Download ppt "Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05."

Similar presentations


Ads by Google