350 likes | 507 Views
Beginning C for Engineers Fall 2005. Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05. Homework, etc. Read Chapter 5 HW4 The project will be posted next week. Details to follow…. Functions. Recall that a C program is a collection of functions.
E N D
Beginning C for Engineers Fall 2005 Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05
Homework, etc. • Read Chapter 5 • HW4 • The project will be posted next week. Details to follow…
Functions • Recall that a C program is a collection of functions. • every C program must have a function called main • program execution always begins with function main • any other functions are subprograms and must be called
More About Functions • it is not considered good practice for the body block of function main to be long • function calls are used to do tasks • 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
Where are functions? • located in libraries • Ex: The square root function is in the math.h library - need to #include <math.h> to use it. discriminant = sqrt ( b * b – 4 * a * c); OR • written by programmers
HEADER FUNCTION EXAMPLE RESULT FILE OF CALL <stdlib.h> abs(int i) a = abs(-6); a = 6 <math.h> 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 <stdio.h> printf(…) printf(“Hello, World”); Hello, World scanf(…) scanf(“%d”, &number); number = input
Two Kinds of Functions Value-Returning Void 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 aseparate statement. 7
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 ); value-returning function example void function example
Any user-defined function consists of 3 parts: • Function declaration (a.k.a. prototype) • 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 • Function definition • Heading = return type, function name, parameter list • Body = actual code • Function call • Using the function
What is in a heading? type of returned value name of function says no parameters int main ( ) { return 0; } 10
Every C function has 2 parts int main ( ) { stmt_1; … stmt_n; return 0; } heading body block 11
Function Calls • one function calls another by using the name of the called function together with ( ) containing an argument list • a function call temporarily transfers control from the calling function to the called function • when the function’s code has finished executing, control is transferred back to the calling block
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; }
Functions that return values • Sometimes a function computes a value needed by the rest of the program • Functions must be able to return computed values before they terminate. • 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 • Examples: x = y + sqrt(20); c = max(a, b);
Program with Two Functions main function square function
Function Definition Return Function Parameter Parameter Type Name Type Name int Square ( int n ) header { int sq = n * n; body return sq; }
Using the Square function #include <stdio.h> 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 ; }
Rest of the program /* Define function */ int Square ( int n ) { int s; s = n * n; return s; }
Output of the Program Enter a number: 15 The square of 15 is 225 Goodbye
Functions that return values • If a function returns a value, the last statement executed must be a return statement. • Syntax: return <expression>; • 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; }
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);
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; }
void functions • 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. • The most common use of a void function is to print something.
Syntax To Call a void Function 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.
Example of a void function #include <stdio.h> /* 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; } /* 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”); }
Example of a void function #include <stdio.h> /* 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; } /* 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”); } }
Parameter List • is the means used for a function to share information with the block containing the call • use commas to separate multiple parameters • each parameter needs a type and name
Classified by Location Arguments Parameters a.k.a. “Actual Parameters” a.k.a. “Formal Parameters” Always appear in the functionheading,or functionprototype. Always appear in afunction callwithin the calling block.
Example – What’s the output? #include <stdio.h> void fun (int b, int c, int a); int main() { int a = 1, b = 3, c = 5; 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
Example – What’s the output? #include <stdio.h> void fun (int b, int c, int a); int main() { int a = 1, b = 3, c = 5; 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.
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) • 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
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 <stdio.h> 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; } Output 5 10 5 20
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);
Things to Note • 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. Right: c = min(a, b); if (isPrime(n)) Wrong: min(a, b); isPrime(n);
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)