Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Week 10 & 11. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or.

Similar presentations


Presentation on theme: "Functions Week 10 & 11. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or."— Presentation transcript:

1 Functions Week 10 & 11

2 Modular Programming 6.1

3 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection of statements to perform a task Motivation for modular programming: –Improves maintainability of programs –Simplifies the process of writing programs

4 Modular programming In simpler terms: big programs get complicated. Small programs are simpler Key idea: Decomposition –Break big complicated sets of instructions into smaller, simpler modules

5 Modular Programming

6 Example: program without functions #include void main (void) { /*Farenheit-to-Celcius*/ double degF, degC; printf(“Enter degrees F: “); scanf(“%f”, &degF;) /* F-to-C conversion:*/ ratio = 5.0 / 9.0;/* We will unify this*/ degC = (degF-32)*ratio;/* set of statements to*/ /* make a new function.*/ printf(“%f degrees F are %f degrees C\n”, degF, degC); } What if we need this conversion step in many different places in our program?

7 Example: program with functions #include double F_to_C (double degreesF); void main (void) { /*Farenheit-to-Celcius*/ double degF, degC; printf(“Enter degrees F: “); scanf(“%lf”, &degF;) degC = F_to_C (degF); printf(“%lf degrees F are %lf degrees C\n”, degF, degC); } double F_to_C (double degreesF) { const double ratio = 5.0 / 9.0; return (degreesF-32)*ratio; } Declare the function (“Function prototype”) Call the function when you need it Define the function

8 Function A collection of statements that performs a specific task. Commonly used to break a problem down into small manageable pieces. In C, there are 2 types of function: –Library functions –User-defined functions

9 Library Functions “Built-in" functions that come with the compiler. The source code (definition) for library functions does NOT appear in your program. To use a library function, you simply need to include the proper header file and know the name of the function that you wish to use. –#include compiler directive

10 Library Functions (cont.) Libraries under discussion at this time: Compiler directivePurpose Character classification and conversion Math functions Data conversion Time functions

11 Library Functions: Math Functions Required header: #include Example functions FunctionPurpose abs(x)returns the absolute value of an integer. pow(x,y)calculates x to the power of y. If x is negative, y must be an integer. If x is zero, y must be a positive integer. pow10(x)calculates 10 to the power of x. sqrt(x)calculates the positive square root of x. (x is >=0)

12 Library Functions: Example 1 1.#include 2.#include 3.#include 4.int main() 5.{ 6.double area, radius; 7. printf("This program calculates the area of a circle.\n”); 8. printf("What is the radius of the circle? ”); 9. scanf (“%lf”, &radius); 10. area=3.14159 * pow(radius,2.0); 11. printf("The area is %lf \n.”, area); 12. getch(); 13. return 0; 14.}

13 Library Function: Example 2 1.#include 2.#include 3.#include 4.main(){ 5.int nom1,nom2, result; 6. printf("Enter two numbers”); 7.scanf (“%d %d”, &nom, &nom2); 8.if ((nom1<0)||(nom2<0)) 9.printf(“negative number/s”); 10. 11. else 12. { 13. result= sqrt(nom1 + nom2); 14. printf("The square root of %d + %d is %d”, nom1, nom2, result);} 15. }

14 Library Functions (cont.) A collection of specialized functions. C promotes code reuse with predefined classes and functions in the standard library The functions work as a black box: sqrt(x) x=4 2

15 More Mathematical Library Functions 3.11

16 More Mathematical Library Functions Require math.h header file Take double as input, return a double Commonly used functions: sin Sine cos Cosine tan Tangent sqrt Square root log Natural (e) log abs Absolute value (takes and returns an int)

17 More Mathematical Library Functions These require stdlib.h header file rand() : returns a random number ( int ) between 0 and the largest int the compute holds. Yields same sequence of numbers each time program is run. srand(x) : initializes random number generator with unsigned int x

18 Exercise Week 10_1 Easy access of function explanation Refer to Lab 10, Exe. 2, No. 2in pg. 92. Trace the output

19 User-Defined Functions User-defined functions are created by you, the programmer. Commonly used to break a problem down into small manageable pieces. You are already familiar with the one function that every C program possesses: int main() –Ideally, your main( ) function should be very short and should consist primarily of function calls. Main Program Function 1Function 3Function 2

20 User defined function – function called

21 Functions – whats, hows Defining and Calling Functions 6.2

22 Functions Function is a “black-box”, a mini program with –A set of inputs –An output –A body of statements It performs one well-defined task (e.g. printf only do the printing process) We can also use functions in a menu-driven program

23 Function concepts & example Calculate the average of four numbers (a, b, c and d)

24 Three steps in using functions 1.Declare the function –Known as function declaration or function prototyping –Write a function prototype that specifies: The name of the function The type of its return value Its list of arguments and their types 2.Define the function –Known as the function definition or function implementation –Write the block of statements (body) of the function to define processes should be done by the function 3.Call the function –Known as the function call or function invocation –Call the name of the function in order to execute it

25 Three steps in using functions

26 Defining and Calling Functions (2 nd and 3 rd steps) Function definition: statements that make up a function Function call: statement causes a function to execute We’ll get back to step #1 soon! – function prototype

27 Function Definition Definition includes: –return type: data type of the value that function returns to the part of the program that calls it –name: name of the function. Function names follow same rules as variables –parameter list: variables containing values passed to the function –body: statements that perform the function’s task, enclosed in {}

28 Function Definition

29 Function Return Type If a function returns a value, the type of the value must be indicated: int main() If a function does not return a value, its return type is void : void printHeading() { printf("Monthly Sales\n”); }

30 Function Return Type void function cannot be used in an expression because it does not return any value. It can only be used as a statement. Example: If given function definition as below: void greeting (void) { printf (“Hello”); return; } Function call below would be an error: result = greeting();//Error! greeting() is a void //function

31 Function Return Type Formal parameters are variables that are declared in the header of the function definition Actual parameters are the expressions in the calling statement When making a function call, the formal and actual parameters must match exactly in type, order and number The parentheses is compulsory, even when no parameters present. This is the way, how the compilier knows an identifier either it is a function or a variable –Example: greeting;//Error, greeting is a function. So, it //must have the () even though no parameter //is present

32 Calling a Function To call a function, use the function name followed by () and ; printHeading(); When called, program executes the body of the called function After the function terminates, execution resumes in the calling function at point of call.

33 Calling a Function - example Function definition Function call Any of the three function calls above are valid *Functions that return a value can be used in an expression or as a statement

34 Flow of Control- void function with parameters

35 Flow of Control- function that returns a value

36 Calling Functions main can call any number of functions Functions can call other functions Compiler must know the following about a function before it is called: –name –return type –number of parameters –data type of each parameter

37 Function Prototypes – step #1 6.3

38 Function Prototypes (or, declaration) Ways to notify the compiler about a function before a call to the function: –Place function definition before calling function’s definition –Use a function prototype (function declaration) – like the function definition without the body Header: void printHeading() Prototype: void printHeading();

39 (Program Continues) Function Prototypes - example Function prototypes /*This program 6.5 has three functions: main, First and Second*/ #include /*Function Prototype*/ void first (); void second (); int main() { printf ("I am starting in function main.\n"); first();/*Call function first*/ second(); /*Call function second*/ printf ("Back in function main again.\n"); getch(): return 0; }

40 Program (Continued) Function definition Function Prototypes - example /************************************* * Definition of function first. * * This function displays a message. * *************************************/ void first() { printf("I am now inside the function first.\n”); } /************************************* * Definition of function second. * * This function displays a message. * *************************************/ void second() { printf("I am now inside the function second.\n”); }

41 Prototype Notes Place prototypes near top of program Program must include either prototype or full function definition before any call to the function – compiler error otherwise When using prototypes, can place function definitions in any order in source file

42 Exercise Week 10_2 Draw a structure diagram for Program 6-5 from slide 39-40 Refer to Lab 11, Exe. 1, No. 1(i) and 1(i)i in pg. 95-96. Solve the problem

43 Sending Data into a Function 6.4

44 Sending Data into a Function Can pass values into a function at time of call: c = pow(a, b); Values passed to function are arguments Variables in a function that hold the values passed as arguments are parameters Giving information to a function call is also known as parameter passing

45 A Function with a Parameter Variable void displayValue(int num) { printf ("The value is %d\n”, num); } The integer variable num is a parameter. It accepts any integer value passed to the function.

46 (Program Continues) A Function with a Parameter Variable - example /*This program demonstrates a function with a parameter*/ #include /*Function Prototype*/ void displayValue (int); int main() { printf ("I am passing 5 to displayValue.\n"); displayValue(5); /*Call displayValue with argument 5*/ printf ("Now I am back in main.\n"); getch(); return 0; }

47 A Function with a Parameter Variable - example /********************************************************* * Definition of fucntion displayValue. * * It uses an integer parameter whose value is displayed. * **********************************************************/ void displayValue (int num) { printf("The value is %d\n", num); } (continued)

48 The function call passes the value 5 as an argument to the function. A Function with a Parameter Variable (cont..) printf("The value is %d\n", num);

49 Other Parameter Terminology – recap! A parameter can also be called a formal parameter or a formal argument An argument can also be called an actual parameter or an actual argument

50 Parameters, Prototypes, and Function Headers For each function argument, –the prototype must include the data type of each parameter inside its parentheses –the header must include a declaration for each parameter in its () void evenOrOdd(int); //prototype void evenOrOdd(int num) //header evenOrOdd(val); //call

51 Function Call Notes Value of argument is copied into parameter when the function is called A parameter’s scope is the function which uses it Function can have multiple parameters There must be a data type listed in the prototype () and an argument declaration in the function header () for each parameter Arguments will be promoted/demoted as necessary to match parameters

52 Exercise Week 10_3 Refer to Lab 11, Exe. 4, No. 2 in pg. 103. Solve the problem What is the output of this program? #include /* Function prototype */ void showDouble(int); int main(){ int num; for (num = 0; num < 10; num++) showDouble(num); getch();; return 0; } /*Definition of function*/ void showDouble(int value) { printf (“%d\t”, value); printf (“%d\n”, value * 2); }

53 Passing Multiple Arguments When calling a function and passing multiple arguments: –the number of arguments in the call must match the prototype and definition –the first argument will be used to initialize the first parameter, the second argument to initialize the second parameter, etc.

54 (Program Continues) Passing Multiple Arguments - example #include /* Function prototype */ void showSum(int, int, int); int main() { int value1, value2, value3; /*Get three integers*/ printf("Enter three integers and I will display "); printf("their sum: "); scanf("%d %d %d", &value1, &value2, &value3); /*Call showSum passing three arguments*/ showSum(value1, value2, value3); getch(); return 0; }

55 Program (continued) Passing Multiple Arguments - example /*********************************** * Definition of function showSum. * * It uses three integer parameters.* * Their sum is displayed. */ void showSum (int num1, int num2, int num3) { printf ("%d", num1+num2+num3); }

56 The function call passes value1,value2, and value3 as a arguments to the function. Passing Multiple Arguments (cont..) printf ("%d", num1+num2+num3);

57 Exercise Week 10_4 #include /*Function prototype*/ void func1(double, int); int main(){ int x = 0; double y = 1.5; printf(“%d %lf\n”, x, y); func1 (y, x); printf(“%d %lf\n”, x, y); getch(); return 0; } void func1(double a, int b){ printf(“%lf %d\n”, a, b); a=0.0; b=10; printf(“%lf %d\n”, a, b);; } Refer to Lab 11, Exe. 4, No. 1 in pg. 103. Solve the problem What is the output of this program?

58 Passing Data by Value 6.5

59 Passing Data by Value Pass by value: when an argument is passed to a function, its value is copied into the parameter. Changes to the parameter in the function do not affect the value of the argument –After the function call completed, the original data remain unchanged

60 Passing Information to Parameters by Value Example: int val=5; evenOrOdd(val); evenOrOdd can change variable num, but it will have no effect on variable val 5 val argument in calling function 5 num parameter in evenOrOdd function

61 Pass by value example

62 Passing expression by value When passing an expression, the expression is evaluated first, then the result is passed to the called function

63 Exercise Week 10_5 Refer to Lab 11, Exe. 2, No. 2 in pg. 97. Solve the problem

64 The return Statement 6.6

65 The return Statement Used to end execution of a function Can be placed anywhere in a function –Statements that follow the return statement will not be executed Can be used to prevent abnormal termination of program In a void function without a return statement, the function ends at its last }

66 (Program Continues) The return Statement - example /* This program uses a function to perform division. * * If division by zero is detected, the function returns.*/ #include //Function prototype void divide (double, double); int main() { double num1, num2; printf("Enter two numbers and I will divide the first\n"); printf("number by the second number: "); scanf("%lf %lf", &num1, &num2); divide (num1, num2); getch(); return 0; }

67 Program (continued) Return to called function The return Statement - example /****************************************************** * Definition of function divide. Uses two parameters: * * arg1 and arg2. The function divides arg1 by arg2 * * and shows the result. If arg2 is zero, however, the * * function returns. * ******************************************************/ void divide (double arg1, double arg2) { if (arg2 == 0.0) { printf("Sorry, I cannot divide by zero.\n"); return; } printf("The quotient is %lf\n", (arg1/arg2)); }

68 Returning a Value From a Function 6.7

69 Returning a Value from a Function A function can return a value back to the statement that called the function. You've already seen the pow function, which returns a value: double x; x = pow(2.0, 10.0);

70 Returning a Value From a Function In a value-returning function, the return statement can be used to return a value from function to the point of call. Example: int sum(int num1, int num2) { double result; result = num1 + num2; return result; }

71 A Value-Returning Function int sum(int num1, int num2) { double result; result = num1 + num2; return result; } Return Type Value Being Returned

72 A Value-Returning Function int sum(int num1, int num2) { return num1 + num2; } Functions can return the values of expressions, such as num1 + num2

73 (Program Continues) Returning a Value From a Function Returning Function - example /* This program uses a function that returns a value */ #include /* Function prototype */ int sum (int, int); int main() { int value1 = 20, /*the first value*/ value2 = 40,/*the second total*/ total; /*to hold the total*/ /*Call the sum function, passing the contents of value1 and value2 as arguments. Assign the return value to the total variable.*/ total = sum(value1, value2); /*Display the sum of the values.*/ printf("The sum of %d and %d is %d\n", value1, value2, total); getch(); return 0; }

74 Program 6-12 (continued) Returning Function - example /******************************************** * Definition of function sum. This function * * returns the sum of its two parameters. * ********************************************/ int sum (int num1, int num2) { return num1 + num2; }

75 The statement total = calls the sum function, passing value1 and value2 as arguments. The return value is assigned to the total variable. sum value2 value1 total Returning a Value From a Function Returning Function - example

76 Returning a Value From a Function The prototype and the definition must indicate the data type of return value (not void ) Calling function should use return value: –assign it to a variable, or –send it to printf, or –use it in an expression Code after a return statement is never executed

77 The following function always returns 10 int square (int a) { return 10; n = n * n; return n; } This line causes the control back to the calling function and ignores the rest of the lines These two lines are ignored and never been executed

78 Exercise Week 10_6 Refer to your solution for Lab 11, Exe. 4, No. 1 pg 102 Change your solution to use return int in function maximum(). Call Maximum function using the following call techniques: –assign it to a variable –send it to printf –use it in an expression

79 Local and Global Variables 6.8

80 Local and Global Variables Variables defined inside a function are local to that function. They are hidden from the statements in other functions, which normally cannot access them. Because the variables defined in a function are hidden, other functions may have separate, distinct variables with the same name.

81 Local and Global Variables - example /* This program shows that variables defined in a function are hidden from other functions. */ #include void anotherFunction(); /*Function prototype*/ int main() { int num = 1;/*local variable*/ printf("In main, num is %d\n", num); anotherFunction(); printf("Back in main, num is %d\n", num); getch(); return 0; } /******************************************************************** Definition of anotherFunction. It has a local variable, num, whose * *initial value is displayed. * ********************************************************************/ void anotherFunction() { int num = 20; /*local variable*/ printf("In anotherFunction, num is %d\n", num); }

82 Local and Global Variables - example

83 When the program is executing in main, the num variable defined in main is visible. When anotherFunction is called, however, only variables defined inside it are visible, so the num variable in main is hidden. Local and Global Variables - example

84 Local Variable Lifetime A function’s local variables exist only while the function is executing. This is known as the lifetime of a local variable. When the function begins, its local variables and its parameter variables are created in memory, and when the function ends, the local variables and parameter variables are destroyed. This means that any value stored in a local variable is lost between calls to the function in which the variable is declared.

85 Global Variables and Global Constants A global variable is any variable defined outside all the functions in a program. The scope of a global variable is the portion of the program from the variable definition to the end. This means that a global variable can be accessed by all functions that are defined after the global variable is defined.

86 Global Variables and Global Constants You should avoid using global variables because they make programs difficult to debug. Any global that you create should be global constants.

87 Global constants defined for values that do not change throughout the program’s execution. Global Constants - example #include

88 The constants are then used for those values throughout the program. Global Constants - example

89 Initializing Local and Global Variables Local variables are not automatically initialized. They must be initialized by programmer. Global variables (not constants) are automatically initialized to 0 (numeric) or NULL (character) when the variable is defined.

90 Local vs. Global example I

91 Local vs. Global – example II

92 Local vs. Global – example III

93 Exercise Week 10_7 Refer to Lab 11, Exe. 3, No.1 in pg. 100. Solve the problem

94 Static Local Variables 6.9

95 Static Local Variables Local variables only exist while the function is executing. When the function terminates, the contents of local variables are lost. static local variables retain their contents between function calls. static local variables are defined and initialized only the first time the function is executed. 0 is the default initialization value.

96 (Program Continues) Local Variables #include

97 In this program, each time showLocal is called, the localNum variable is re-created and initialized with the value 5. Local Variables - example printf(“localNum is %d\n”, localNum);

98 A Different Approach, Using a Static Variable (Program Continues) #include

99 statNum is automatically initialized to 0. Notice that it retains its value between function calls. Using a Static Variable - example printf(“statNum is %d\n”, statNum);

100 If you do initialize a local static variable, the initialization only happens once. See Program 6-22… Using a Static Variable - example printf(“statNum is %d\n”, statNum);

101 Exercise Week 10_8 Given the following programs compare the output and reason the output. #include void showVar(); int main ( ) { for (int count=0;count<10; count++) showVar(); getch(); return 0; } void showVar() { static int var = 10; printf(“%d\”n, var); var++; } #include void showVar(); int main ( ) { for (int count=0;count<10; count++) showVar(); getch(); return 0; } void showVar() { int var = 10; printf(“%d\”n, var); var++; }

102 Default Arguments 6.10

103 Default Arguments A Default argument is an argument that is passed automatically to a parameter if the argument is missing on the function call. Must be a constant declared in prototype: void evenOrOdd(int = 0); Can be declared in header if no prototype Multi-parameter functions may have default arguments for some or all of them: int getSum(int, int=0, int=0);

104 Default arguments specified in the prototype (Program Continues) Default Arguments - example #include printf(“\n”);

105 Program 6-23 (Continued) Default Arguments - example printf(“*”); printf(“\n”);

106 Default Arguments If not all parameters to a function have default values, the defaultless ones are declared first in the parameter list: int getSum(int, int=0, int=0);// OK int getSum(int, int=0, int); // NO When an argument is omitted from a function call, all arguments after it must also be omitted: sum = getSum(num1, num2); // OK sum = getSum(num1,, num3); // NO

107 Exercise Week 10_9 Refer to Lab 11, Exercise 2, No.5 in pg. 99. Solve the problem

108 Using Reference Variables as Parameters 6.11

109 Using Reference Variables as Parameters A passing technique that passes the address of a variable instead of its value A mechanism that allows a function to work with the original argument from the function call, not a copy of the argument –Causes side effect, when the called function changes a value, it actually changes the original variable in the calling function Allows the function to modify values stored in the calling environment Provides a way for the function to ‘return’ more than one value

110 Passing by Reference The argument (actual parameter) must be an address of a variable int n; fun (&n); /* &n means “address of a variable n” */ The formal parameter must be a pointer void fun(int *x)/* x is a pointer variable */ ( /* function body */ } Changes to a reference variable are made to the variable it refers to

111 Passing by reference – example I

112 The * here in the prototype indicates that the parameter is a reference variable. Here we are passing value by reference. (Program Continues) Passing by Reference – example II /* This program uses a reference variable as a function parameter */ #include /* Function prototype. The parameter is a reference variable */ void doubleNum (int *refVar); int main () { int value = 4; printf("In main, value is %d\n", value); printf("Now calling doubleNum...\n"); doubleNum(&value); printf("Now back in main. value is %d\n", value); getch(); return 0; }

113 The * also appears here in the function header. Program 6-24 (Continued) Passing by Reference - example /************************************************* * Definition of doubleNum * * The parameter refVar is a reference variable. * * The value in refVar is doubled. */ void doubleNum (int *refVar) { *refVar *= 2; }

114 Pointer – the concept How the passing by reference works? To understand this, let’s first look at the concept What we have used so far is normal variable or also known as data variable. A data variable contains a value (e.g. integer number, a real number or a character) Pointer is a variable that contains the address of another variable. This is also known as address variable

115 Pointer – the concept (cont.) Since pointer is also a variable, it is declared like the data variable The difference is, we need to place an asterisk (*) before the pointer Example int n = 5; // n is a normal variable (or data variable) int *p = &n; // p is a pointer that holds the address of // variable n

116 Pointer – the concept (cont.) There are two special operators for pointers: address operator and indirection operator Address operator, & –Get the address of a variable –Example: &n Meaning: “give me the address of variable n” Indirection operator, * –Get the value of a variable where its address is stored in the pointer –Example: *ptr Meaning: “give me the value of variable where its address is stored in the variable ptr” –Pointer declaration also uses the asterisk (*). But don’t get confused as pointer declaration and indirection operator are different.

117 Address and Indirection Operators

118 Another example – how passing by reference works

119 Exercise Week 10_10 Refer to Lab 11, Exe. 2, No.3 in pg. 98. Solve the problem

120 Thank You Q & A


Download ppt "Functions Week 10 & 11. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or."

Similar presentations


Ads by Google