LAB 7 FUNCTION PART 2 School of Computer and Communication Engineering Universiti Malaysia Perlis 1
OBJECTIVES 1. To differentiate the file scope and block scope. 2. To write recursive function. 3. To use library functions in a C program. 4. To write user-defined library function. NOTES Part 1 Scope 1. An identifier declared outside any function has file scope. Such an identifier is known (i.e., accessible) in all functions from the point at which the identifier is declared until the end of the file. Global variables, function definitions, and function prototypes placed outside a function all have file scope. 2. Block Identifiers defined inside a block have block scope. Block scope ends at the terminating right brace () of the block. Local variables defined at the beginning of a function have block scope as do function parameters, which are considered local variables by the function. 3. Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. This can be illustrated in Figure 1. #include <stdio.h> int x; /* Global variable, declared outside any function. */ void funct(void); main() x = 0; /* x isn't declared in main()*/ x++; /* increment x */ printf("the value of x is %d\n", x); funct(); /* x will be different after funct() */ printf("the value of x is %d\n", x); void funct(void) x++; /* x isn't declared in funct()*/ x += 3; Figure 1 Global variable 2
Sample output: The value of x is 1 The value of x is 5 4. Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. This can be illustrated in Figure 2. #include <stdio.h> void funct(void); main() int x; /* Local variable, declared inside any function. */ x = 0; x++; /* increment x */ printf("the value of x is %d\n", x); funct(); /* x will be the same after funct() */ printf("the value of x is %d\n", x); void funct(void) int x; /* Local variable, declared inside any function. */ x++; x += 3; Sample output: The value of x is 1 The value of x is 1 Figure 2 Local variable 5. If we want a variable to persist throughout the running of the program. This is where the static type comes in. The use of the static variable allows the variable to be incremented and for the value to be remembered throughout the program. This can be illustrated in Figure 3. 3
#include <stdio.h> int times_called(void); main() int i; for (i = 0; i < 10; i++) printf("times_called() has been called %d times\n",times_called()); int times_called(void) /* The variable is declared and defined once*/ static int i = 0; ++i; /* Incrementing the variable */ return i; Figure 3 Static variable Sample output: times_called() has been called 1 times times_called() has been called 2 times times_called() has been called 3 times times_called() has been called 4 times times_called() has been called 5 times times_called() has been called 6 times times_called() has been called 7 times times_called() has been called 8 times times_called() has been called 9 times times_called() has been called 10 times Part 2 Recursive function 1. A recursive function is a function that called itself. 2. The recursive functions should be used very carefully because when a function called by itself it enters into infinite loop. And when a function enters into the infinite loop, the function execution never gets completed. We should define the condition to exit from the function call so that the recursive function gets terminated. 4
#include<stdio.h> int factorial(int); int main() int fact, n; printf("enter any positive integer:\n"); scanf("%d", &n); fact = factorial(n); printf("factorial of %d! is %d\n", n, fact); return 0; int factorial(int n) if (n == 0) return 1; else return(n * factorial(n-1)); Sample output: Enter any positive integer: 3 Factorial of 3! = 6 Figure 4 An example of a recursive function 3. In the above example program, the factorial() function call is initiated from main() function with the value 3. Inside the factorial() function, the function calls factorial(2), factorial(1) and factorial(0) are called recursively. The complete execution process of the program in Figure 4 is shown in Figure 5. 5
Figure 5 Execution process of the program in Figure 4 (source: http://www.btechsmartclass.com) 6
Part 3 Library functions 1. C supports many built-in functions. Table 1 and Table 2 lists mathematical functions available in C. Most of the functions expect one or more type double arguments and return a type double result. Table 1 Some mathematical Library Functions 7
Table 2 More mathematical library functions 2. The program in Figure 6 shows how to use some of the mathematical functions in Table 1 and Table 2. 8
#include <stdio.h> #include <math.h> int main() double x,y; printf("acos(0.5)\t%f\n", acos(0.5)); printf("asin(0.5)\t%f\n", asin(0.5)); printf("cos(0.3)\t%f\n", cos(0.3)); printf("cosh(0.5)\t%f\n", cosh(0.5)); printf("sin(0.5)\t%f\n", sin(0.5)); printf("sinh(0.5)\t%f\n", sinh(0.5)); printf("tan(0.5)\t%f\n", tan(0.5)); printf("tanh(0.5)\t%f\n", tanh(0.5)); printf("abs(-7)\t\t%f\n", abs(-7)); printf("ceil(-3.3)\t%f\n", ceil(-3.3)); printf("exp(0.5)\t%f\n", exp(0.5)); printf("fabs(-3.3)\t%f\n", fabs(-3.3)); printf("floor(-3.3)\t%f\n", floor(-3.3)); printf("log(0.5)\t%f\n", log(0.5)); printf("log10(0.5)\t%f\n", log10(0.5)); printf("pow(2,3)\t%f\n", pow(2,3)); printf("sqrt(2)\t\t%f\n", sqrt(2)); return 0; Figure 6 Trigonometric and hyperbolic functions Sample output: acos(0.5) 1.047198 asin(0.5) 0.523599 cos(0.3) 0.955336 cosh(0.5) 1.127626 sin(0.5) 0.479426 sinh(0.5) 0.521095 tan(0.5) 0.546302 tanh(0.5) 0.462117 abs(-7) 0.462117 ceil(-3.3) -3.000000 exp(0.5) 1.648721 fabs(-3.3) 3.300000 floor(-3.3) -4.000000 log(0.5) -0.693147 log10(0.5) -0.301030 pow(2,3) 8.000000 sqrt(2) 1.414214 9
Part 4 User-defined library function 1. We have seen how the availability of C s standard libraries simplifies program development. However, the standard libraries are not extensive enough to handle every programming need. In fact, one can use the C preprocessor directive #include to make userdefined libraries as well. 2. To create a user-defined library, we must first make a header file (.h extension) a text file containing all the information about a library needed by the compiler when compiling a program that uses the facilities defined in the library. Precisely this type of data is found in system header files such as stdio.h, math.h, and string.h. 3. In Code Block, you must create a new project and put them in appropriate folders i.e. header files into header s folder and source files into source s folder as shown in Figure 7. Figure 7 A project with user-defined library function 4. Basically we will have 3 separate files in a project e.g. shapes.h (Figure 8), shapes.c (Figure 9) and main.c (Figure 10). /*shapes.h*/ void horizontalline();//function declaration(prototype) void triangle();//function declaration(prototype) Figure 8 shapes.h 10
EKT 120 Introduction to Computer Programming Laboratory Module /*shapes.c*/ void horizontalline() /*function definition*/ printf("\n*********\n"); void triangle()/*function definition*/ int i, space, rows=6, star=0; /* printing one row in every iteration */ for(i = 1; i <= rows; i++) /* Printing spaces */ for(space = 1; space <= rows-i; space++) printf(" "); /* Printing stars */ while(star!= (2*i - 1)) printf("*"); star++;; star=0; /* move to next row */ printf("\n"); Figure 9 shapes.c /*main.c*/ #include "shapes.h" int main() triangle(); /*function call*/ horizontalline(); /*function call*/ return 0; Sample output: Figure 10 main.c * *** ***** ******* ********* *********** ********* 11
EKT 120 Introduction to Computer Programming Laboratory Module PART 1 STRUCTURED QUESTIONS i. Predict and write the output for the program shown in Figure 11. #include <stdio.h> void function1(int, int); void function2(int *, int); int main() int a = 5; int b = 10; printf("\nbefore function1: a = %d function1(a, b); printf("\nafter function1: a = %d b = %d", a, b); b = %d", a, b); printf("\n\nbefore function2: a = %d b = %d", a, b); function2(&a, b); printf("\nafter function2: a = %d b = %d\n", a, b); return 0; void function1(int p, int q) p = p + 5; q = q + 5; printf("\nwithin function1: p = %d void function2(int *r, int s) *r = *r - 5; s = s -5; printf("\nwithin function2: *r = %d q = %d", p, q); s = %d", *r, s); Figure 11 12
EKT 120 Introduction to Computer Programming Laboratory Module ii. The following questions are based on Figure 12. #include <stdio.h> void fnfun1(int, int*); int main(void) int ia=3,ib=6; printf("before fun 1\n ); printf( ia = %d ib = %d \n,ia,ib); fnfun1(ia, &ib); printf( \n\nafter fun 1\n ); printf( ia = %d ib = %d \n,ia,ib); return 0; void fnfun1(int iaa,int *ibb) ++iaa; --*ibb; printf("\n\ninside fnfun1\n ); printf( iaa = %d ibb = %d \n,iaa,*ibb); Figure 12 a) Identify and state the parameter which is passed by value and by reference to function fnfun1(int, int*). b) State the difference between the passing parameter by value and by reference in functions. c) Predict the output of Figure 12. 13
EKT 120 Introduction to Computer Programming Laboratory Module PART 2 PROGRAMMING QUESTION i. Write and test a recursive function that finds the greatest common divisor of two integers m and n, using Euclid's algorithm: a) Find the integer remainder of min (m mod n). a) If the remainder is 0, then n is the largest integer divisor of both m and n. b) If the remainder is not 0, replace m with n and n with the integer remainder from the original division. Repeat the steps until the remainder is 0. For example, what is the greatest common divisor of 30 and 12? a) The integer remainder of 30/12 is 6. b) The remainder is not 0. c) The integer remainder of 12/6 is 0. Therefore, 6 is the largest integer divisor of both m and n. ii. Write and test a recursive function that returns 1 if an integer is prime and 0 if it is not. You can take advantage of the following facts: a) The integers 1, 2, and 3 are prime. b) Any even integer greater than 2 is not prime. c) If an integer has no divisor less than or equal to its square root, it must be prime. That is, if an integer has a divisor greater than or equal to its square root, it must also have a divisor less than or equal to its square root. Odd integers that are perfect squares, such as 49, have two divisors, each of which is equal to the square root. To implement this algorithm, it is helpful the use two separate functions, one of which has a single parameter associated with the integer to be tested. The prototypes should look like this: int Is_Prime(int n); int Get_Prime(int n,int m); where n is the integer to be tested and m is a trial divisor. Only the function Is_Prime is called directly. Then Is_Prime conducts some preliminary tests on n and calls Get_Prime only if the other tests cannot determine whether n is prime. Of these two functions, only Get_Prime is called recursively. 14
EKT 120 Introduction to Computer Programming Laboratory Module iii. Snell's Law describes the refraction (bending) of light as it passes from one medium to another. If the refractive index of the incident medium is n j and that of the refracting medium is n r, and the angle of incidence i and angle of refraction r of a ray of light, measured from the perpendicular to the boundary between the two mediums, are related by n i sin i = n r sin r Figure 13 illustrates the geometry of Snell s Law. Write a program that asks the user to provide two refractive indices and the angle of an incident ray and then calculates the angle of a refracted ray. Use mathematical library functions to construct the formula. Figure 13 Geometry for Snell s Law of refraction The formula to determine the angle of the refracted ray is: Table 3 gives the angles of refraction for some common materials when a light ray is directed from air, which has a refractive index equal to 1, into the material. Table 3 15
EKT 120 Introduction to Computer Programming Laboratory Module Sample output: Input indices of refraction for incident and refracting medium (water, glass or diamond) separated by spaces: 1 1.50 Input angle of incident: 20 Refracted angle = 13.8 degree iv. Create a project named calculator and write a header file named calculator.h, a function definition file, calculator.c and a main.c into the project. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result (For division, if the denominator is zero, output an appropriate message). Sample output : Please enter 2 integers: 4 2 Please enter an operator (+, -, *,/): * Result : 8 Do you want to continue : y or n?y Please enter 2 integers: 2 0 Please enter an operator (+, -, *,/): / ERROR denominator is zero!cannot divide by zero Do you want to continue : y or n?n Define function prototypes in calculator.h: a) double add(double,double); b) double multiply(double,double); c) double divide(double,double); d) double subtract(double,double); 16