# Functions I - PowerPoint PPT Presentation Download Presentation Functions I

Functions I Download Presentation ## Functions I

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Functions I • Functions are a collection of statements that perform a specific task. • C has built-in functions, e.g. sqrt( x). • C also allows user defined functions. • Using functions helps organize code, make it easier to use from program to program. • Can call the same function from many places in the program. Thus we only write the function once but we use it multiple times.

2. Functions II • A program in C consists of one or more functions. • A valid program must have exactly one function named main. • Program execution always starts at main function. • Each function performs a certain job; • Examples: Calculate square root Determine if a number is odd Determine if a number is prime Determine if a string is palindrome

3. Function General Form • Is comprised of a function heading and a function body. • Syntax: • A function is defined as follows: Returned_data_type function_name (Parameters_list)// Heading { statement1; statement2; //function body … statementn; } • The returned data type is a data type such as int, double, char, float….. • The function type could be void in this case nothing expected to be returned. Thus there will be no need for return statement. • Semantics: it is coming after some examples.

4. Examples void print2lines ( ) { printf(“**************************\n"): printf(“**************************\n"): } int sum2int (int a, int b) // int parameters are declared { int c; c = a + b; return c; }

5. Example II double maximum(double A, double B) { if (A>B) return A; else return B; } • The function type is double. • The parameters are A and B are also of type double. • They are called formal parameters.

6. Example III void printOnes(int k) { int i; for (i=1; i<=k; i++) printf(“1”); } • The function type is void and it has one parameter of type int. The name of the parameter is k. • How it is used?

7. Function Semantics • Once a function is invoked (called) by other function, • the parameters in the called function definition are replaced by the actual parameters. • The control then is transferred temporarily to the called function. • The statements in the called function are executed from the beginning of the function definition until the end of the function is reached or a return statement is executed. • The control is then is transferred to the statement immediately after where the function was invoked.

8. Complete Program Example #include <iostream.h> void printOnes(int k) { int i; for (i=1; i<=k; i++) printf(“1”); } void main( ) { int n; scanf(“%d”, & n); printf( “entring function\n”); printOnes(n); // printOnes is invoked (called) n replaces k in the function printf(“finished function”); } • The format of the program as in the example: • First the include statement, • the definitions of the functions and • then the main function. • This is not the only way.

9. return statement • The return statement is used to specify the value of a function. • The general form of the return statement is: return expression; • The return statement always terminates function execution with function value equals to expression value. • The type of the returned value must be compatible with the value in the function header. • main function can also return a value.

10. Example: Function Definition and Calling #include <iostream.h> int maximum(int x, int y) {// The function returns an integer value if (x>y) return x; else return y; } void main( ){ printf(“%d”, maximum(2,10)); int a=7, b=87; printf(“%d”, maximum(a,b)); printf(“%d”, maximum(a,17)); printf(“%d”, maximum(a,2) +2*maximum(3,5)%5); printf(“%d”, maximum(maximum(2,3),2); a=maximum(3,8); b = maximum(2,4); }

11. Same Function With Void Type and its Calling #include <iostream.h> void maximum(int x, int y) { if (x>y) printf(“%d”, x); else printf(“%d”, y); } void main( ){ printf(“%d”, maximum(2,10)); //compiler error a=maximum(3,6); //compiler error maximum(2,4); // ok } • Be careful if the called function returns a value or it does not return a value.

12. Designing Functions • What do I want this function to do? • What parameters do I need? • What are the data types of these parameters? • Should this function return a single value? if so what is the data type of the returned value? • What local variables need to be defined within this function? • Let us look at some examples.

13. Write a function to determine if an integer is even or odd • What parameters are needed? • Do we need to return a value? If so what is this value? int even(int X) { if (X%2==0) return 1; else return 0; }

14. ExampleII • Write a function to find the smallest factor > 1 of a given integer number. • What parameters are needed? • Do we need to return a value? If so what is this value? int f(int X) { for (int I=2; I<=X; I++) if (X%I==0) return I; }

15. Example III • Write a function to compute 1+2+3+ … +n. • What parameters are needed? • Do we need to return a value? If so what is this value? int add(int n) { int sum=0; for(int I=1; I<=n; I++) sum+=I; return sum; }

16. Example IV • Write a function to compute xy where x is double and y is integer. • What parameters are needed? • Do we need to return a value? If so what is this value? int myPower(double x, int y) { double result=1; for(int I=1; I<=y; I++) result*=x; return result; }

17. Example v • Write a function to compute F=5/9*C-32. • The function should take as a parameter the C value and returns the equivalent F value. double convert(double C) { return 5/9.0*(C-32); }

18. One function uses another function • Write a function to compute n! and then use it to write another function to compute combination of (m, n). int fact(int n) { int result=1; for(int I=1; I<=n; I++) result*=I; return result; } int comb(int m, int n) { return fact(m)/(fact(n)*fact(m-n)); }

19. One function uses other functions • Write a function to compute 1/1!+(1+2)/2!+(1+2+3)/3!+…+(1+2+3+…n)/n! • We divide the application into functions: • Add: to sum up the numbers from 1 to n • Fact: to compute the factorial double f(int n) { double sum=0; for(int I=1; I<=n; I++) sum+= ((double) add(I))/fact(I); return sum; }

20. Prime numbers • Write a function to test if a number is a prime or not a prime. int prime(int x) { int I; for(I=2; I<=x-1 && x%I; I++); if (I==x) return 1; else return 0; }

21. Using prime function • Write a function that takes 2 integers a, b and prints all prime integers between a and b. void printPrimes(int a, int b) { for(int I=a; I<=b; I++) if (prime(I)) printf(“%d”, I); }

22. Top Down Methodology • Divide a large problem into small problems and solve each small problem as a function. That is each function implements a piece of the larger problem solution. • Sometimes the solution to a piece of the problem must be made available to solve other pieces. • e.g., the function computes a value needed by other functions in the program.

23. More On Function Definitions • Cannot be nested inside on another. • Therefore, because main is a function itself, they are placed before the main function. • They can come after the main function in this case a function prototype is required. • What is a function prototype?

24. Function Prototypes • Act similar to a variable declaration. • Occur before main. • Look similar to function heading except that it ends in a semicolon and it does not require the parameter name, just the data type. voidprint2lines ( ); intsum2int (int, int); If the parameter name is included, it is ignored.

25. //comments # include library files function prototype(s) void main ( ) { statement(s) } function definition(s) { statement(s) // body } Format

26. From where a Function gets Data?

27. Example: PromptAndRead() • Write a function to prompt and extract next integer • The function needs no parameters but it returns a value. int PromptAndRead() { printf( "Enter number (integer): "): int Response; scanf(“%d”, &Response); return Response; }

28. Problem • Definition • Input two numbers that represent a range of integers and display the sum of the integers that lie in that range • Design • Prompt user and read the first number • Prompt user and read the second number • Calculate the sum of integers in the range smaller...larger by adding in turn each integer in that range • Display the sum

29. Range.cpp #include <iostream.h> int PromptAndRead(); int Sum(int a, int b); int main() { int FirstNumber = PromptAndRead(); int SecondNumber = PromptAndRead(); int RangeSum = Sum(FirstNumber , SecondNumber); printf("The sum from %d”, FirstNumber); printf (“to %d is “, SecondNumber); printf(“%d \n”, RangeSum); return 0; }

30. Range.cpp cont. // PromptAndRead(): prompt & extract next integer int PromptAndRead() { printf( "Enter number (integer): "): int Response; scanf(“%d”, Response); return Response; } // Sum(): compute sum of integers in a ... b int Sum(int a, int b) { int Total = 0; for (int i = a; i <= b; ++i) { Total += i; } return Total; }

31. Global vs. Local Variables • A variable that is declared within a block is “local” to that block and may only be accessed within that block. • Therefore, a variable declared in a function definition (either heading or body) is local to that function. • Several functions may use the same identifiers as variable names, but each is stored in a different memory space. • Global variables are declared outside all functions and may be accessed from any of the functions.

32. Identifier Scope Rules • file scope • defined outside function, known in all functions • function scope • can only be referenced inside a function body • block scope • declared inside a block. • Begins at declaration, ends at } • function prototype scope • identifiers in parameter list.

33. Example on Local Variables void f() { int i = 1; // i is defined in the function printf( “%d\n”, i); // prints out 1 { int j = 10; // j is defined in the block printf(“%d %d\n”, i, j); // prints out 1 10 i = 2; printf(“%d%d \n”, i, j ); // prints out 2 10 } printf(“%d\n”, i); // prints out 2 printf(“%d\n”, j); // error }

34. Example 2 void f() { { int i = 1; printf(“%d\n”, i); // prints out 1 { printf(“%d\n”, i); // prints out 1 char i = 'a'; printf(“%d\n”, i); // prints out a } printf(“%d\n”, i); // prints out 1 } printf(“%d\n”, i); // error }

35. Lifetime of Variables • The lifetime of a variable is when memory has been allocated for it. • Dynamic – the memory is allocated from point of declaration and is deallocated when the block is finished. • What was previous stored in that variable is lost. • Static – the memory is not deallocated when the block is finished. • What was previously stored remains. Automatically initialized to zero. Example: static int alpha;

36. Passing Parameters • Pass by value – a copy of the value from the actual parameter is sent to the formal parameter of the function. The function cannot change the value of the actual parameter. • Pass by reference – the same memory location is shared by actual parameter and the formal parameter. The function can change the value that is stored in the actual parameter. • Pass by reference parameters are denoted by an & in the function heading and the function prototype.

37. Pass by Reference - Example • Suppose your know the length of the sides of a rectangle and you want a single function to calculate both the perimeter (المحيط) and the area of the rectangle. • Your function would need 4 parameters, rect_length, rect_width, perimeter, and area. • The parameters rect_length and rect_width would be pass by value because you do not want the function to change them. • The parameters perimeter and area would be passed by reference because the function would calculate them.

38. Example (cont.) • The Function Definition would be void calcAreaPeri(float rect_length, float rect_width, float &perimeter, float &area) { perimeter = 2* rect_length + 2 * rect_width; area = rect_length* rect_width; }

39. Example (cont.) • The function prototype would be void calcAreaPeri(float, float, float&, float&); • The function call would be calcAreaPeri(len, width, p, a); /* assuming len, width, a and p have been declared. */

40. Example (cont.) void main ( ) { float len, width, p = 0, a = 0; printf(“Please enter the length and width \n"): scanf(“%d%d”, len, width); calcAreaPeri(len, width, p, a); printf(“A rectangle of length %d ”, len) printf(“ and width of %d”, width); printf(“ has a perimeter of %d”, p ) printf( “ and an area of %d\n”, a); }

41. Value vs. Reference • With pass by value, the actual parameter may be a variable, constant (literal or symbolic), or an expression. • With pass by reference, the actual parameter must be a variable name. • Pass by reference parameters are denoted by an & in the function heading and prototype. void someFunction(int& c, float g, int& d) void someFunction(int& , float , int& );

42. Using void Swap(int a, int b) { int Temp = a; a = b; b = Temp; return; }

43. Consider the following: int main() { int Number1 = PromptAndRead(); int Number2 = PromptAndRead(); if (Number1 > Number2) { Swap(Number1, Number2); } printf( "The numbers in sorted order: %d , %d \n”, Number1, Number2); return 0; } Would the numbers be sorted? Why?

44. Reconsider the example Using void Swap(int &a, int &b) { int Temp = a; a = b; b = Temp; } Passed by reference -- in aninvocation the actualparameter is given ratherthan a copy

45. Consider the second definition of swap int i = 5; int j = 6; Swap(i, j); printf(“%d%d\n”, i, j); int a = 7; int b = 8; Swap(b, a); printf(“%d %d\n”, a,b);

46. Problem • Write a program to add two rational numbers. • You need GCD function to keep the answer in its simple form. int gcd(int x, int y) { while (x != y) { if (x > y) swap(x, y); y -= x; } return x; }

47. Passing Arrays to Functions • specify the name without any brackets int myArray[ 24 ]; myFunction( myArray, 24 ); • array size is usually passed to function • Arrays passed call-by-reference • value of name of array is address of the first element • function knows where the array is stored • modifies original memory locations • Individual array elements passed by call-by-value • pass subscripted name (i.e., myArray) to function • Function prototype: void modifyArray( int b[], int arraySize ); • Parameter names optional in prototype • int b[]could be simplyint [] • int arraysize could be simply int

48. Examples of Function with arrays • A function to print contents of an array void Printarray(float [ ], int); void main ( ) { float myarray[ 30] ={1.1,2.2,2.1,2.5,9.2}; Printarray(myarray, 30); } // function to print contents of an array void Printarray(float numbarray[ ], int size) { for (int j = 0; j < size ; j++) cout<<numbarray[j]<<“ “;

49. Find the smallest element in an array int List_Min(int A[], int asize) { int SmallestValueSoFar = A; for (int i = 1; i < asize; ++i) if (A[i] < SmallestValueSoFar ) SmallestValueSoFar = A[i]; return SmallestValueSoFar ; } • What happens as a result of the following? int Number = {2,3,6,1,5,9}; cout << List_Min(Number, 6) << endl; int List = {9, 12, 45}; cout << List_Min(List, 3) << endl; • Home work: Write a function Find_Min(int A[], int size) to compute the location of the minimum value.

50. Some Useful Functions void DisplayList(const int A[], int n) { for (int i = 0; i < n; ++i) { cout << A[i] << " "; } cout << endl; } void GetList(int A[], int &n, int MaxN =10) { for (n = 0; (n < MaxN) && (cin >> A[n]); ++n); }