Presentation is loading. Please wait.

Presentation is loading. Please wait.

Quiz 2.

Similar presentations


Presentation on theme: "Quiz 2."— Presentation transcript:

1 Quiz 2

2 1 2 3

3 Lecture 9 Function

4 Outline What is Function Function Definition
Standard (Predefined) Functions User-Defined Functions Flow of Execution

5 Functions - Mathematical View
X Function Returned value

6 Function Input and Output

7 Example

8 Call power Call power power Call power

9 Function Syntax Function define syntax:
<return type> <function name> (param …) { <statements> } param …  <data type> <variable name> , …

10 Example

11 Why we use function Provides a layer of ‘abstraction’
Reduce code line Use one block of code several time. Building Programs from Existing Programs Standard library For example : stdio, math, rand … Provides a layer of ‘abstraction’ Helps manage complexity Smaller blocks of code Easier to read

12 Why we use function Divide and conquer
Construct a program from smaller pieces or components Smaller pieces sometimes called function Each piece more manageable than the original program Divide and Conquer

13 Functions Every C program starts with main() function
Functions could be Pre-defined library functions e.g., printf, sin, tan Programmer-defined functions e.g., my_printf, area

14 Pre-defined library functions
<math.h> Defines common mathematical functions e.g. sin, cos. sqrt, pow <stdio.h> Defines core input and output functions e.g. printf, scanf <time.h> Defines date and time handling functions e.g. time, clock <stdlib.h> Defines pseudo-random numbers generation functions e.g. rand, srand

15 C mathematical functions
double      pow( double base, double exp); Computes the value of base raised to the power exp double      sin( double arg ); Computes sine of arg (representing angle in radians) double      cos( double arg ); Computes cosine of arg (representing angle in radians) double      tan( double arg ); Computes tangent of arg (representing angle in radians) ...

16 An example

17 An example

18 Random numbers generation functions
int rand(); Returns a uniformly distributed pseudo-random integral value between ​0​ and RAND_MAX (0 and RAND_MAX included) RAND_MAX : Expands to an integer constant expression equal to the maximum value returned by the function rand(). This value is implementation dependent. #define RAND_MAX /*implementation defined*/ srand() should be called before any calls to rand() to initialize the random number generator void srand( unsigned seed ); Initializes the built-in random number generator used to generate values for rand() with the seed value seed

19 An Example #include <stdio.h> #include <stdlib.h> int main(void) { unsigned int seed; /* Declare variables. */ int k; /* Get seed value from the user. */ printf("Enter a positive integer seed value: \n"); scanf("%u",&seed); srand(seed); /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

20 An Example #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(0)); //use current time as seed for random generator /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

21 Random Numbers in [a b] Generate a random number [0 .. 7]
x = rand() % 8; Generate a random number [ ] x = 10 + rand() % 8; rand() % (b-a+1) + a;

22 User- defined function

23 Functions in C Queries: Return a value
sin(), fabs() Commands: do some tasks, do not return any value or we don’t use the value printf(...) scanf(...)

24 Functions in C Three steps to use functions in C Function declaration
Introduce the function to compiler Function definition What the function does Function call Use the function

25 Function Definitions Function definition format
return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier Return-value-type: data type of the result void – indicates that the function returns nothing Parameter-list: comma separated list, declares parameters A type must be listed explicitly for each parameter No input: empty parameter list () or void

26 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; } A function that calculates the product of two numbers double product(double x, double y) { double result; result = x * y; return result; } The function definition declares the return data type, its name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Contrast this with the function prototype.

27 Function Definitions Function definition format (continued)
return-value-type function-name( parameter-list ) { declarations and statements } Declarations and statements: function body (block) Variables can be declared inside blocks Functions can not be defined inside other functions

28 Producing output Function definition format (continued)
return-value-type function-name( parameter-list ) { declarations and statements } Query functions Produce output To produce an output Declare output type Generate the output by return

29 The return command To generate a result by a function
return <value>; return <expression>; Only one value can be returned If noting returned return; Or until reaches right brace

30 The return command return finishes running the function
Function can have multiple return Only one of them runs each time The type of the returned value = the result type Otherwise, cast

31 Functions that do not return a value
Use the return type of void void functionName( DataType arg_1,…) void functionName() void functionName( void)

32 Function call Command function Query function
<function name> (inputs); Query function <variable> = <function name>(inputs); Inputs should match by function definition Functions are called by another function Function call comes inside in a function

33 Example void my_info(void){
printf("My name is Ahmad Ahmadi\n"); printf("My student number: \n"); } int main(void){ my_info(); printf(" \n"); my_info(); return 0;

34 Function Call – An Example
If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored int GetUserInput (void); /* function prototype*/ int main(void) { int input; input = GetUserInput( ); return(0); /* return 0; */ } However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value We can also call a function inside another function printf("User input is: %d", GetUserInput( ));

35 N = f(pi*pow(r,2), b+c) + d;
Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used, N = f(pi*pow(r,2), b+c) + d;

36 Using Functions (continued)
This is a parameter Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used , N = f(pi*pow(r,2), b+c) + d; This is an argument This is also an argument

37 Quick review Define a function:
<return type> <function name>(<param> …) { <Statement> } <param>  <data type> <value name> , …

38 Quick review If in function execute return, function will be terminate. Function data type and return type must be same. If function type be void, can be use return; to terminate function.

39 Quick review In order to call a function:
<function name>(<param> …);

40 Example

41 Example Enter a number: 5 Enter a number: 4 Sum is 9
Press any key to continue

42 Example

43 Example

44 Example

45 Example

46 Example

47 Example

48 Definitions Parameter:– a declaration of an identifier within the '()' of a function declaration Used within the body of the function as a variable of that function Argument:– an expression passed when a function is called; becomes the initial value of the corresponding parameter

49 Scope of variables

50 Scope of Variables Until now, Variables Scope of variable
Are declared in the start of functions Are used any where in the function after declaration Can we used them outside of function? Can we used them in other functions? Scope of variable A range of code that the variable can be used  Variable cannot be used outside of its scope Compile error

51 Scopes vs. Blocks Scopes are determined by Blocks Variables
Start with { and finished by } Example: statements of a function, statement of a if or while, … Variables Can be declared in a block Can be used in the declared block Cannot be used outside the declared block The Declared block is the scope of the variable

52 Example

53 Nested Scopes/Blocks Scopes can be nested
Example: Nested if, nested for, …

54 Variables in Nested Blocks
All variables from outer block can be used inner blocks Scope of outer block contains the inner block Variables in inner block cannot be used in outer block Scope of the inner block does not contains the outer block

55 Example

56 Same Variables in Nested Block
If a variable in inner block has the same identifier of a variable in outer block The inner variable hides the outer variable Changing inner variables does not change outer variable

57 Local Variables All defined variables in a function are the local variable of the function Can ONLY be used in the function, not other functions

58 Global Variables Global variables are defined outside of all functions
Global variables are initialized to zero Global variables are available to all subsequent functions

59 Example

60 Example

61 Argument Passing

62 Argument Passing In C language we study two type of argument passing.
Pass by value Pass by reference

63 Call by value In call by value mechanism
The values are copied to the function Only the copy of variable’s value (copy of actual parameter’s value) is passed to the function. If we change values in the function The copied version is changed The original value does not affected Any modification to the passed value inside the function will not affect the actual value

64 Example Enter two numbers to calculate its sum: 4 9 4 + 9 = 13 Press any key to continue #include <stdio.h> int calSum(int,int); /*function protototype*/ int main(void) { int sum, num1, num2; printf("Enter two numbers to calculate its sum:\n"); scanf("%d%d",&num1,&num2); sum = calSum(num1,num2); /* function call */ printf("\n %d + %d = %d", num1, num2, sum); return(0); } int calSum(int val1, int val2) /*function definition*/ int sum; sum = val1 + val2; val2 = 100; return sum; 4 num2 9 num1 13 sum 4 num2 9 num1 ? sum ? num2 num1 sum 100 val2 9 val1 13 sum 4 val2 9 val1 13 sum 4 val2 9 val1 ? sum

65 Call by reference Call by reference
In this method, the reference (memory address) of the variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value

66 Call by reference 10 b a 5 b 1 a b a main -5 b a main 5 b 1 a CalByVal
#include <stdio.h> void CalByVal(a, b) { a = 0; b = 10; } void CalByRef(int *a, int *b) // CalByRef(int *p, int *q) *a = 0; *b = -5; int main(void) int a = 1, b = 5; printf("Before cal CalByVal: a = %d, b = %d\n", a, b); CalByVal(a, b); printf("After cal CalByVal: a = %d, b = %d\n", a, b); printf("Before cal CalByRef: a = %d, b = %d\n", a, b); CalByRef(&a, &b); printf("After cal CalByRef: a = %d, b = %d\n", a, b); return 0; /* Exit program. */ CalByVal 10 b a CalByVal 5 b 1 a CalByRef b a main -5 b a main 5 b 1 a

67 Recursive function

68 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type A recursive function is a function invoking itself, either directly or indirectly Recursion: A → B → C → D → A Concept of recursive function (generally): A recursive function is called to solve a problem The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer if (stopping case) solve it else reduce the problem using recursion

69 Recursion Recursive Algorithm
An algorithm uses itself to solve the problem There is a basic problem with known solution Recursive Algorithms are implemented by recursive functions Recursive function A function which calls itself There is a condition that it does not call itself

70 Recursion Any problem that can be solved recursively can also be solved iteratively (using loop) Recursive functions are slow and takes a lot of memory space compared to iterative functions So why bother with recursion? There are 2 reasons: Recursion approach more naturally resembles the problem and therefore the program is easier to understand and debug Iterative solution might not be apparent

71 An Example: xy In this example, we want to calculate x to the power of y i.e. xy If we analyze the formula for xy, we could see that xy could be written as (x being multiplied to itself, y times) An example is 24, which can be written as 24 = 2 x 2 x 2 x 2 (in this case, x = 2, y = 4) 24 could also be rewritten as 24 = 21 x where 21 = 2 (i.e the number itself) Therefore, we could divide the problem into two stage: Simplest case: when y = 1, the answer is x Recursive case, we need to solve for x * x(y-1)

72 Introduction Factorial GCD n! = n x n-1 x … x 2 x 1
GCD(a, b) = Euclidean Algorithm GCD(a, b) = GCD(b, a mod b) There is a simple (basic) problem which we can solve it directly (without recursion) Factorial: 1! = 1 GCD: b == 0

73 Fibonacci solution

74 Fibonacci x = 5; temp = 1; temp = 1 + Fib(1); return temp;
temp = Fib(2) + Fib(1); return temp; x = 5; temp = 1; temp = ; return temp; x = 5; temp = 1; temp = 1 + Fib(1); return temp; x = 1; temp = 1; return temp; x = 5; temp = 1; temp = 1 + Fib(1); return temp; x = 5; temp = 1; temp = Fib(2) + Fib(1); return temp; x = 5; temp = 1; temp = ; return temp; int Fib (int x) { /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (x > 2) /* other cases */ temp = Fib(x-1) + Fib(x-2); return temp; } x = 4; temp = 1; temp = 2 + 1; return temp; x = 4; temp = 1; temp = 2 + Fib(2); return temp; x = 4; temp = 1; temp = Fib(3) + Fib(2); return temp; x = 5; temp = 1; temp = 3 + 2; return temp; x = 5; temp = 1; temp = Fib(4) + Fib(3); return temp; x = 5; temp = 1; temp = 3 + Fib(3); return temp;

75 Fibonacci 5 fib(5) fib(3) fib(4) fib(3) fib(2) fib(2) fib(1) fib(2)
int Fib (int n) { /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (n > 2) /* other cases */ temp = Fib(n-1) + Fib(n-2); return temp; } fib(5) 3 2 fib(3) fib(4) 1 1 2 1 fib(3) fib(2) fib(2) fib(1) 1 1 fib(2) fib(1)

76 Print Right to Left Example

77 Print Left to Right Example

78 Recursion solution of xy

79 Factorial solution

80 GCD solution

81 Indirect recursion What we have seen are direct recursion
A function calls itself directly Indirect recursion A function calls itself using another function Example: Function A calls function B Function B calls function A

82 Example

83 Storage Class

84 Storage Classes Storage class(Refers to the lifetime of a variable)
How memory is allocated for the variable Until when the variable exists How it is initialized Storage classes in C  Automatic External  Static Register

85 Storage Classes Refers to the lifetime of a variable
Local variables only exist within a function by default. When calling a function repeatedly, we might want to Start from scratch – reinitialize the variables The storage class is ‘auto’ Continue where we left off – remember the last value The storage class is ‘static’ Another two storage classes (seldomly used) register (ask to use hardware registers if available) extern (global variables are external)

86 Syntax storage_classes variable_type variable_name Example: int auto
float double char auto register static extern Example:

87 Storage Classes: Automatic
Automatic storage class Variable created when program enters its block Variable destroyed when program leaves block Only local variables of functions can be automatic Automatic by default keyword auto explicitly declares automatic

88 Example Auto example: 1 Press any key to continue

89 Storage Classes: External
All global variables are external by default Are generated when program starts Are destroyed when program finishes Usage of keyword “extern” To use global variables in other files To emphasize that variable is global This usage is optional

90 Storage Classes: Static
Keyword “static” comes before them For local variables: 1) Generated in the first run of the block 2) Destroyed when program finishes 3) Initialized If no value  initialized by 0 Only initialized in the first run of the block

91 Static storage class However the static keyword can be applied to a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds

92 Example Static example: 1 3 5 Press any key to continue

93 Storage Classes: Register
Keyword “register” comes before them Can be used for local variables Compiler tries to allocated the variable in registers of CPU But does not guaranteed Registers are very fast and small memories Improve performance


Download ppt "Quiz 2."

Similar presentations


Ads by Google