Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Four: Functions: Built-in, Parameters and Arguments, Fruitful and Void Functions Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing. Joachim Zumbrägel Universität Duisburg-Essen Faculty of Engineering, Department Electrical Engineering and Information Technology Computer Engineering Procedural Programming/Lab4 1
Getting familiar with Functions A function is a self contained program that carries out some specific purpose. Every C program consists of one or more functions, and if you recall from the first section one of these functions is the int main() function. Execution of a C program always begins with the int main() function. Any other functions used will be subordinate to the int main() function, and perhaps to one another. So, why should we actually use functions? Well, one of the main advantages of using functions is that they are used to divide up a program code into easy manageable sized portions. So they basically work like subtasks within a program. They can be executed (i.e. when it is called ) as many times as required from various points of the program. Once a function has carried out its intended action, control will be returned back to the point of the program from where it was accessed. Therefore, without the ability to use functions within our programs, our code would end up being much larger. Every function has a name which not only identifies it but is also used to call it for execution in a program. The name is global, but may not necessarily be unique in C. Nevertheless, functions with different actions should be supposed to have different names in general. The rules governing the name of a function are same as those used for a variable. The name of a function can be a sequence of letters and digits and should reflect its action in general, for example, you might name a function as CountUpper() which counts all upper case letters. Functions can either be user defined or they can be built in in a standard library file, such as the pow() function used to raise a number to a certain power in the math.h library file. Note: To use the functions which are located in a C library file, you must include the corresponding header file at the start of the program. Procedural Programming/Lab4 2
Declaring a Function We already know that we need to declare a variable prior to using it. Similarly, you can t use a function without declaring it first. Functions are declared by first telling the compiler about its some characteristics, i.e. the name of the function, the return type of the function, the number of arguments and their data types. Syntax: return-type function-name(type1 argument1,.,typen argumentn); For example, double pow(double x, double y); Explanation: The function pow() returns a value of type double. It has two arguments, x and y. The first argument x, should be of data type double, the second argument y, should also be of data type double. Exercise 4.1: Write a function declaration for a function named afunc() which returns a value of type integer and has two arguments of type double. Function Definition The function definition consists of a function definition header, followed by the function body. The function body is composed of statements that make up the function, delimited by braces. Syntax: return-type function-name(type1 argument1,.,typen argumentn) function body (statements and declarations) The function body consists of statements and declarations which allow the function to carry out its necessary task. The body of a user defined function is programmed very much similarly as the body of the main() function. Procedural Programming/Lab4 3
Explanation: return type: This defines the data type a function returns. A function might or might not return a value. If a function returns a value, that should be of a valid data type. The return data type can be of integer, float, character or any other valid data type. A returning variable data type should have a matching return type data type. There can be functions which don t return a value. For such type of functions, the return type is void. void is a keyword of C language. If a return type is not mentioned with a function, the default return type value is of int data type i.e. it will return an integer value. function name: Like naming variables, same rules apply while naming functions. It s generally a good practice to use function names which are self explanatory such as square, squareroot, circlearea etc. argument list: The argument list consists of information needed to pass to a function. Some functions don t need any type of information to perform the task. Consequently, the argument list will be empty for such functions. Arguments to a function should be of a valid data type e.g. double radius, int number etc. function body: The body of the function consists of declarations and statements. The task of the function is performed within the body of the function. Calling a Function within a Program In order to call a function, the calling program needs to reference the function name along with its arguments. When a function is called within a program, the control is immediately passed on to the function. The parameters are then substituted with values and the function is executed. The control is then transferred back to the called function, along with the returned values. For example, the statement within a program in the main() function outcome = factorial(num); calls the function factorial() and passes a copy of the value stored in the variable num from the function factorial(). Note: While calling a function, we don t need to mention the return value data type or the data types of arguments. Procedural Programming/Lab4 4
Exercise 4.2: Considering the given function declaration void func(int x, char y); State which of the following calls to the function are correct calls, and if not then why not? a. func(22.4, 49); b. func(3.14159); c. func(19.5, a ); d. func(52.3, 19, b ); e. func(62, c ); Sending Information to a Function Passing Arguments Whether a function is user defined or a standard library function, they can be further classified depending on its definition as: 1. Those which return a value 2. Those which don t return a value Assume, we have a function which computes the square of an integer value such a function will return the square of the given integer value. Similarly, we might have a function to display some type of information on the standard output screen and such type of a function is not supposed to return any value to the calling program. Functions that don t return a value and use in the declaration If you don t want a function to return a value, use the keyword void as the return type in its prototype. This means the function has no arguments. As another example, consider the following int getchar(void); Procedural Programming/Lab4 5
The function getchar(void) is a function returning an integer type value but does not take any arguments. Exercise 4.3: Write a function declaration for a function named voidfunc() which does not return a value. The function should have two arguments. The first argument should be a double and the second an integer. The keyword void can be used as a type specifier when defining a function which is not supposed to return anything (example 1) or when a function definition does not include any arguments (example 2). It s not compulsory to write this key word, but it s usually a good programming practice to use this. Such functions are also commonly used to display instructions to a user. Example 1: /* example: using void functions */ #include<stdio.h> void add(int a, int b); int main() add(3,2); void add(int a,int b) int sum; sum = a + b; printf( sum: %d\n,sum); Procedural Programming/Lab4 6
Example 2: Following program shows us an example of the definition of the void function Display_Stars(): /* example: using void functions */ #include <stdio.h> void Display_Stars(); int main() printf( \n ); for (int x = 1; x <= 5; ++x) Display_Stars(); Printf( \n ); printf( \n ); void Display_Stars(void) for (int y = 1; y <= 10; ++y) printf( * ); Explanation: This function has no arguments and does not return a value. So, its definition header does not have a parameter list and specifies the return type as void. It displays ten stars * using a for loop. Each iteration prints one star *. The last statement of the function body, the return statement, passes control back to the point of the program where the function Display_Stars() was called or executed, namely the int main() function. Exercise 4.4: Trace the output of the above program example and write it down below. Procedural Programming/Lab4 7
Exercise 4.5: Write a function header for a function which does not have any arguments and does not return a value. Returning a Value from a Function Arguments are used to pass values to a called function. A return value can be used to pass a value from a called function back to the function that called it. Example: /* example: value returning functions */ #include <stdio.h> int addnums(int x, int y); int main() int n1, n2; int sum = 0; printf( Enter the first number:\n ); scanf( %d,n1); printf( Enter the second number:\n ); scanf( %d,n2); sum = addnums(n1, n2); printf( n1 + n2 = %d\n, sum); int addnums(int x, int y) return x + y; Explanation: The above program uses the function addnums() to add two numbers of type integer. The return value is added by indicating its data type, here an int, in front of the function name in both the function prototype and the header. Procedural Programming/Lab4 8
Exercise 4.6: Write a function header for a function inttofloat that takes an integer number as an argument, and returns the result in floating point. Exercise 4.7: Write a function named hypotenuse which takes two double precision, floatingpoint arguments, side1 and side2, and returns a double precision, floating point result. Exercise 4.8: Write a function named largest which takes three integers values a, b and c, and then returns an integer. Procedural Programming/Lab4 9
Exercise 4.9: Write a program which uses a function to calculate the square of a user entered number. The function should take the user entered number as an argument. Procedural Programming/Lab4 10
Passing Arguments to a Function There are two approaches to pass the information to a function through arguments: by Value by Reference Passing Arguments by Value In C, arguments are passed by value, by default. Passing by value means that an argument's value is passed to a function, and not to the argument itself. Example: The following program illustrates passing arguments by value: /* example: pass by value */ #include<stdio.h> void func(int a) printf( a is %d\n,a); a = 5; printf( a is %d\n,a); int main() int b = 8; printf( b is %d\n,b); func(b); printf( b is %d\n,b); Passing Arguments by Reference Passing by reference means that the function parameters are declared as references rather than the normal variables. As we saw in an earlier session, printf() function used this method of argument passing by using format specifiers, also known as conversion specifiers. Please take note, this topic will be covered later on in detail in the Session on Pointers. Procedural Programming/Lab4 11
Variable Scope in functions Local Variables A variable which is declared within a function has a local scope which means the variable is known only inside the function. Any statement outside that function in which the variable is declared cannot change the value of that variable. Example: The following program shows how the local variables are used within a program when defined locally in a function. Here in the int main() function. /* example: local variables */ #include <stdio.h> int main() int x = 5; int y = 20; x++; if (y > 0) printf("x is %d", x); // value of x defined in main() can be seen if (y > 0) int x = 50; // value of x is defined locally in this block printf("\nx is %d", x); // value of x (i.e. 50) dies here printf(" \nx is %d", x); // value of x is now visible Exercise 4.10: Trace the value of the variable x in the above program example and write down its value after each output statement. Procedural Programming/Lab4 12
Global Variables A variable which is declared outside a functions body has a global scope which means the variable is known to any function defined after the declaration of that variable. So, due to its globality, any function coming after the declaration of that global variable can change the value of that global variable.example: The following program shows how the global and local variables both are used within a program. /* example: global variables */ #include <stdio.h> int y = 5; // Global definition int func(); int main() int value = 0; y++; // Increment Global variable printf("global value of y is: %d",y); value = func(); printf("\nlocal value of y returned from the function is: %d", value); int func() int y = 10; y++; return y; // Internal declaration // Internal variable Exercise 4.11: Trace the value of the variable y in the above program example and write down its value after each output statement. Procedural Programming/Lab4 13
Exercise 4.12: Find and correct the errors in the following: a) int result(double i, double j) int sum; sum = i + j; b) int sum(int x) if (x == 0) else sum(x - 1) + x; c) void g(float i); double i; printf( i:%f,i); Procedural Programming/Lab4 14
Recursive Functions The programs we discussed so far were generally structured having functions which call one another in a disciplined, hierarchical manner. But sometimes it s useful to have functions call themselves, known as recursive functions. A recursive function is a function that calls itself, either directly or indirectly through another function. Recursive problem solving approaches have a number of elements in common. A recursive function is called to solve a problem. Example: The following example uses a recursive function to print the Fibonacci series. Except first two terms, every other term in a Fibonacci series, is the sum of two previous terms. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 and so on. Here for example: 8 = 3 + 5. /* recursive fibonacci function */ #include<stdio.h> int fibonacci(int); main() int n, i = 0, x; printf("please enter number of fibonacci terms you want to print:\n"); scanf("%d",&n); printf("fibonacci series\n"); for ( x = 1 ; x <= n ; x++ ) printf("%d\n", Fibonacci(i)); i++; int Fibonacci(int n) if ( n == 0 ) else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) ); Procedural Programming/Lab4 15
Exercise 4.13: Write a program which uses a fibonacci() function that uses a loop instead of recursion to print the Fibonacci series. Procedural Programming/Lab4 16