40
This is part of the book COMPUTER PROGRAMMING THE C LANGUAGE by Adriana ALBU Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5

COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

This is part of the book

COMPUTER PROGRAMMING

THE C LANGUAGE

by Adriana ALBU

Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5

Page 2: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Chapter 10 User-defined functions

A complex problem is not usually solved by a single group of instructions placed in the main() function. This would imply the writing of a very long and intricate program and, on the other hand, an unnecessary duplication of some sections of code that perform the same task (eventually using different input data). In order to avoid these disadvantages, the problem that must be solved is split into several sub-problems; separated sections of code are written for each sub-problem that has distinct features. These sections of code are in fact the functions. A C program can contain two types of functions:

! predefined functions (or library functions) o this are already implemented to solve simple and well-defined

problems; o they are part of the standard library of the C programming lan-

guage; therefore, a preprocessor directive #include followed by the name of the header file that contains a certain function is necessary when that function is used in a program;

o examples: mathematical functions (math.h): sqrt(), exp(); functions that perform input/output actions (stdio.h, co-nio.h): printf(), scanf(); functions used to process strings (string.h): strlen(), strcpy();

! user-defined functions o these are written by the developer of a program;

o their use makes the program clearer, easier to correct, maintain and modify and allows code reusability.

Therefore, functions are an important feature of the C programming language, representing the location where the entire activity of a program takes place [HS98]. Splitting programs into small units (functions) is the best solution in structuring these programs. Functions are easier to handle and can be used in various configurations [CH96]. A function is a sequence of code that has a name and that performs a certain task. A C program must have at least one function (the main() function,

Page 3: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

2

without which a program cannot be executed), but it can contain many other functions.

10.1 User-defined functions

The following steps must be covered in order to work with user-defined func-tions: ! first, the compiler must be notified that a function will be defined in the

program; this is done through the prototype of the function – several fea-tures of that function, which must be specified before the beginning of the main() function;

! the description of the function contains the definition and the body of that function and is the location where the code that solves the task for which the function was created appears; this implementation of the function can be placed once the main() function ends or before it begins (in the latter case the definition overlaps the prototype);

! the call of the function is in fact the use of that function in the program.

10.1.1 The prototype of a function

The prototype of a function is the first thing that must be specified when a function is created and used. Through the prototype, the name of the function and several information about the data received by the function from outside and about the result generated by the function are mentioned. The compiler will use the prototype in order to verify if the instructions that are related to a certain function use it correctly (otherwise, an error message will be generated).

When the prototype of a function is specified, a line of code with the following general form is used: type_returned_val function_name(type_arg1 name_arg1,

type_arg2 name_arg2, …, type_argn name_argn);

where:

o type_returned_val is the type of the value returned by the function (sent back where the function was called);

o function_name is a valid name, which will be used to call the function (it is the subject of the same rules as a variable’s

Page 4: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

3

name: it must begin with a letter or an underscore, it cannot con-tain the characters #, $ or space, the keywords of the language must be avoided, etc.);

o type_argi name_argi specify the type and the name of each argument received by the function from outside;

o the prototype is followed by the separator ; (semicolon).

The following line of code specifies the prototype of a function called aver-age that will calculate and will return the average of the first n natural numbers (n is a parameter of type int received by the function when it is called): float average(int n);

If the function doesn’t send any result outside, then the type of the returned value is void (this kind of functions are called void functions). The following prototype defines a function that receives an argument of type char, but doesn’t return anything: void a_function(char a);

It is possible to have nothing in front of the name of a function (the type of the returned value is not specified). Attention! In this case it is considered that the function will return an integer value (do not confuse with a function that doesn’t return anything and that has the type void specified). The following function will receive two arguments (one of type float and the other one of type int) and will return an integer value: another_function(float x, int y);

10.1.2 The description of a function

This contains the definition and the body of a function. The definition must be identical to the prototype (same number of arguments, same type of both argu-ments and returned value), but it is not followed by the semicolon separator. The body of the function is the sequence of code that solves the task for which the function was created. The instructions that form the function’s body follows right after the function’s definition and are enclosed by curly brackets. The definition and the body of the function average (previously specified by its prototype) could be: float average(int n){

Page 5: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

4

int i;

float sum=0;

for(i=1;i<=n;i++)

sum=sum+i;

return sum/n;

}

About return

If a function has to return a value, then its body must contain at least one re-turn instruction followed by the value that is returned (as in case of the func-tion average previously presented). The general form for this instruction is: return [expression];

When the instruction return is executed, the function that contains it is im-mediately left and the execution of the program goes back to the instruction that caused the call of the function. If the function returns a value, then the ex-pression that follows after return is executed and the result is sent out-side. If return is not followed by an expression, a variable or a value or even is missing, then the function is left without returning a value (of course, this is the case of a void function). The following function receives as argument a string and displays it in reverse order, without returning anything: void reverse(char *s){

int i;

for(i=strlen(s)-1;i>=0;i--)

printf("%c",s[i]);

}

A function may contain several return instructions; the first one that is en-countered will be executed. These multiple return instructions emerge on different branches of conditional instructions (for instance if… else…) and using them distinct values are returned, accordingly to the path followed by the execution of the program. The following function receives as argument a real number (a float one) and returns its sign (-1 if the number is negative, 0 if it is zero or 1 if it is positive): int signum(float x){

Page 6: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

5

if(x<0) return -1;

else

if(x==0) return 0;

else return 1;

}

About arguments

The arguments (or the parameters of a function) are enclosed by parentheses and are placed right after the name of a function in its prototype and in its defi-nition. Data is transmitted from outside to function through these arguments. They can be used in the function as any other variable that was declared inside that function. Each argument has a name and a type. The type that is specified in the prototype must be identical to the one used when the function is called; the name can be different. The following function returns the product of two integer numbers received as argument: int product(int x, int y){

return x*y;

}

If a function doesn’t accept arguments, then its prototype and its definition will have the type void instead of the list of arguments. The following function doesn’t receive arguments (it returns the sum of the first 5 natural numbers): int sum(void){

int i, s=0;

for(i=1;i<=5;i++)

s=s+i;

return s;

}

10.1.3 The call of a function

The call of a function is required when the function must be used. This is a simple action that is made through the name of the function followed by its

Page 7: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

6

parameters (enclosed by parentheses). The programs that were written in the previous chapters have already called library functions, though the functions were not explicitly discussed. The following instructions call few of these func-tions: printf("This is a library function");

getch();

sqrt(49);

strlen("text");

The call of a user-defined function is made in the same manner. The following instruction calls the function reverse() that was previously defined and that displays a string from right to left: reverse("C Programming");

The parentheses that follow the name of a function when it is called are manda-tory, though the function doesn’t require arguments. For instance, the function that calculates the sum of the first 5 natural numbers (previously defined) is correctly called in this way: sum();

If a function returns a value (as the function sum() does), this value can be used in several ways: ! it is assigned to a variable (it is the right side operand of an assignment): x=sum();

! it is part of an expression (the call of the function is also in the right side of an assignment): average=sum()/5;

! it is a parameter of another function: printf("The sum is: %d", sum());

! it is part of a condition: if(sum()>0) printf("The sum is positive");

! it is lost, because it is neither assigned nor used in an expression (it is obvi-ous that the use of the function in this case has no sense): sum();

Page 8: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

7

If a function requires parameters, these can be (function average(), previ-ously described, is considered as example):

! values: a=average(3);

! variables: n=7;

a=average(n);

! expressions: n=1;

m=2;

a=average(n+m);

The call of a function cannot be the left side operand in an assignment. The following instruction is wrong and will generate a compilation error: sum()=100; //incorrect call

It is not mandatory that the name of the parameters used in the function’s call is identical to the name of the arguments from the prototype of the function (only their number and their type must be the same). Therefore, a function with the prototype void calculate(float x, int y);

can be called: calculate(a,b);

Program 10.1.1 is a complete example of declaring and calling a function. This function calculates and returns the average of the first n natural numbers (it is obvious that the average can be calculated only if n is not zero).

Program 10.1.1 #include <stdio.h> #include <conio.h> float average(int nr); void main(void){

Page 9: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

8

int n=2; if(n!=0) printf("The average is: %.2f",average(n)); else printf("Error: division by zero!"); getch(); } float average(int nr){ int i; float sum=0; for(i=1;i<=nr;i++) sum=sum+i; return sum/nr; }

It is possible to have the definition and the body of a function before the main() function; in this case, the definition and the prototype are overlapping. The semicolon separator from the end of the prototype must be removed be-cause the body of the function follows (enclosed by curly brackets). Pro-gram 10.1.2 presents the same example with the average, but places the descrip-tion of the function average() at the beginning of the program. Attention! If this kind of implementation is chosen, then the main() function must be the last function in the program.

Program 10.1.2 #include <stdio.h> #include <conio.h> float average(int nr){ int i; float sum=0; for(i=1;i<=nr;i++) sum=sum+i; return sum/nr; } void main(void){ int n=2;

Page 10: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

9

if(n!=0) printf("The average is: %.2f",average(n)); else printf("Error: division by zero!"); getch(); }

The call of a function can be performed within any function, not only in the main() function. Example 10.1.3 also calculates the average of the first n natural numbers, but inside the average() function, a function sum()is called, that returns the sum of the first n natural numbers; then the average is calculated and returned.

Program 10.1.3 #include <stdio.h> #include <conio.h> float sum(int nr){ int i; float s=0; for(i=1;i<=nr;i++) s=s+i; return s; } float average(int nr){ return sum(nr)/nr; } void main(void){ int n=2; if(n!=0) printf("The average is: %.2f",average(n)); else printf("Error: division by zero!"); getch(); }

Page 11: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

10

One of the major advantages of functions is that these are written once and could be used (called) many times, generating different results if different pa-rameters are sent to them. In program 10.1.4, function signum() is called three times.

Program 10.1.4 #include <stdio.h> #include <conio.h> int signum(float x){ if(x<0) return -1; else if(x==0) return 0; else return 1; } void main(void){ printf("\n%d", signum(-7.17)); printf("\n%d", signum(0)); printf("\n%d", signum(70)); getch(); }

Return from a function Once the execution of a function ends, the program continues from the point where the function was called. There are two ways a function ends its execution [HS98]:

! the instructions from a function are executed one by one, until the end of the function (the closing curly bracket). The function from program 10.1.5 dis-plays a string from right to left, traversing it character by character. Once the string was entirely displayed, the function has nothing else to do, there-fore it ends and the execution of the program comes back in the main(), at the instruction that follows after the call of the reverse() function.

Program 10.1.5 #include <stdio.h>

Page 12: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

11

#include <conio.h> #include <string.h> void reverse(char *s){ int i; for(i=strlen(s)-1;i>=0;i--) printf("%c",s[i]); } void main(void){ clrscr(); reverse("C Programming"); getch(); }

! the execution of a function is interrupted by a return instruction. This is used both to return a value (in this case it is followed by that value or by an expression) or to increase the efficiency of the function (for instance, a function that searches a character in a string could finish its execution when the first occurrence of that character is found, without losing time to search to the end of the string). This kind of function can contain several return instructions. The function from program 10.1.6 returns 1 if the searched character is found and 0 otherwise.

Program 10.1.6 #include <stdio.h> #include <conio.h> #include <string.h> int search(char *s, char c){ int i; for(i=0;i<strlen(s);i++) if(s[i]==c) return 1; return 0; } void main(void){ char str[20], ch; int found;

Page 13: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

12

printf("Enter the string: "); gets(str); printf("Enter the character: "); scanf("%c", &ch); found=search(str,ch); if(found) printf("The character was found"); else printf("The character doesn’t exist"); getch(); }

10.1.4 The scope of variables

A variable has a certain scope (a context where it is valid and can be used) according to the location where that variable is declared [CH96]. The variable scope refers to its visibility, to who can “see” it (meaning who can use it), to when it is created and when it is destroyed. Two main categories of variables can be distinguished from this point of view: ! local variables:

o are declared within a function; o are created each time the function is called;

o are destroyed when the function ends and it is left; o are available only inside the function, any attempt to access them

outside the function being an error; o are required in order to isolate the functions (generally, a func-

tion should not affect other functions or their variables); a func-tion receives data from outside through its arguments and sends values outside through return instructions; everything else happening within the function’s body is private.

! global variables: o are declared outside any function, at the beginning of the pro-

gram, after the preprocessor directives (#include, #de-fine);

o are available during the entire execution of the program;

Page 14: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

13

o can be accessed and modified by any function of the program;

o are used when more functions of the program must access the same data;

o should be avoided if they are not necessary, because they hold useless the memory during the entire execution of the program and reduce the generality of the functions that use them (those functions cannot be used in other programs because they refer to something that must be defined outside their code) [HS98].

A function is connected to its external environment through its arguments and through the global variables. The arguments received by the function can be handled as local variables.

The values that are used in a function’s call are called actual parameters. When these values arrive inside the function they are called formal parameters.

Program 10.1.7 calculates the average of two numbers and it is an example for all types of variables previously presented. Variable n is a global variable; it is declared at the beginning of the program, it is initialized within the function main() and it is used by the function calculate(). Variables n1, n2 and result are local variables of the function main() and can only be used within this function. n1 and n2 are also actual parameters passed to the func-tion calculate() when it is called. Inside the function they became formal parameters a and b. The function calculate() also has a local variable, m, created at the beginning of the function and destroyed when the function ends.

Program 10.1.7 #include <stdio.h> #include <conio.h> int n; //n – global variable float calculate(float a, float b){ //a, b – formal parameters float m; //m – local variable m=(a+b)/n; return m; } void main(void){

Page 15: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

14

float n1=5, n2=10, result; //n1, n2, result – local variables n=2; result=calculate(n1,n2); //n1, n2 – actual parameters printf("The average is: %.2f", result); getch(); }

It is advisable to use local variables and parameters rather than global variables whenever is possible. For instance, a function that calculates the sum of two numbers can be developed in several ways:

! version 1 – the function can only be used to calculate the sum of the global variables x and y: int x, y;

int sum(void){

return x+y;

}

! version 2 – the function receives two numbers as arguments; it is more general and because it is parameterized, it can be used to calculate the sum of any two numbers: int sum(int x, int y){

return x+y;

}

If a local variable has the same name as a global variable, all the instructions that access the variable within the function where the local variable is declared refer only to the local variable and do not affect the global variable [HS98]. Program 10.1.8 emphasizes this aspect. Once it is run, on the screen is dis-played: x in main: 10

x in function_1: 100

x in function_2: 10

Page 16: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

15

A global variable x is declared; it receives the initial value 10 within the main() function and then it is displayed. In turn, function_1() declares a local variable with the same name, gives it the value 100 and then prints it; the x variable within this function refers to the local variable and not to the global one. The call of function_2() proves this, the global variable x having the same value 10, which was initially established within the main() function.

Program 10.1.8 #include <stdio.h> #include <conio.h> int x; void function_1(void){ int x=100; printf("\nx in function_1: %d", x); } void function_2(void){ printf("\nx in function_2: %d", x); } void main(void){ clrscr(); x=10; printf("\nx in main: %d",x); function_1(); function_2(); getch(); }

Local variables, in turn, can be of two types:

! automatic; ! static.

If nothing else is specified, then the local variables are destroyed when the function ends its execution. This is because they are considered by default automatic.

Page 17: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

16

There is the possibility to keep the content of a variable between two executions of the function that created it. The variable can be accessed only by that func-tion and its content is maintained until the execution of the entire program ends. In other words, a static local variable gives the possibility to store information in a private way (because this information is available only to the function where the variable is defined) and also in a permanent way (the information is available during the entire execution of the program) [BK03]. This is performed using the keyword static in front of the variable’s declaration: static int counter=0;

Program 10.1.9 emphasizes the difference between static and automatic varia-bles. The functions increment1() and increment2() increment and display the value of a counter that receives the initial value 0 at the beginning of these functions. They are repetitively called 10 times in the main() func-tion. The difference between these two functions is the manner of declaring the local variable counter. Within function increment1() it remains auto-matic, but within function increment2() it is declared static; this will main-tain the value of the variable counter, belonging to the function incre-ment2(), from an execution to the next one.

Once the program is executed, on the screen will be displayed: Automatic variable:

1 1 1 1 1 1 1 1 1 1

Static variable:

1 2 3 4 5 6 7 8 9 10

The counter variable receives the initial value 0 at the beginning of each function. It must be specified that if a variable is declared static, this line is executed only when the function is called for the first time (this is the reason why the value of the variable is not altered when the function is recalled).

Program 10.1.9 #include <stdio.h> #include <conio.h> void increment1(void){ int counter=0; counter++;

Page 18: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

17

printf("%d ",counter); } void increment2(void){ static int counter=0; counter++; printf("%d ",counter); } void main(void){ int i; printf("Automatic variable:\n"); for(i=1;i<=10;i++){ increment1(); } printf("\nStatic variable:\n"); for(i=1;i<=10;i++){ increment2(); } getch(); }

10.1.5 Changing the arguments of a function

There are two ways of passing arguments to functions: ! by value;

! by address. By default, the arguments are passed by value (with one exception: the arrays; their passing to functions will be separately discussed); therefore, the arguments used in a function’s call cannot be altered by the code that is executed within the function. This is because the value of the actual parameter (the one used when the function is called) is copied into the formal parameter of the function (parameter that has a temporary aspect). This value can be changed within the function, but because it is only a copy of the value used in the function’s call, these changes have no effect on the actual parameter. Program 10.1.10 creates and initializes a variable x within the main() func-tion and then sends this value to the function pass_val() that increments the

Page 19: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

18

received argument. Variable x is displayed at return from the function in order to see that its value is not changed.

Program 10.1.10 #include <stdio.h> #include <conio.h> void pass_val(int x){ x++; } void main(void){ int x=10; pass_val(x); printf("x=%d", x); //it is displayed x=10 getch(); }

Programs that pass the parameters by value are more compact and have fewer global variables (within functions the formal parameters are similar to local variables) [BK03]. Using this way of passing the arguments, the functions don’t have access to the original variable, but only to their copies. Nevertheless, sometimes the changing of actual parameters is required; in this case they must be passed by address. The address of a variable is sent in the function’s call. The parameter is declared as pointer in the function’s prototype and the variable is indirectly accessed through this pointer [BK03]. This way the changes are made right on the original variable.

Program 10.1.11 emphasizes the passing of arguments by address. The code is very similar to the one used for the passing by value. The first difference that should be noticed emerges at the call of the function pass_adr() that re-ceives as argument the address of the variable x (&x). The second aspect is connected to the prototype of the function, where x is declared as pointer (*x). Finally, the third thing regards the way of handling the variable x within the function (the operations with pointers must be used here): through the instruc-tion (*x)++; the value stored at the address indicated by the pointer is ac-cessed and incremented. Therefore, the changing is made right on the original variable, which is then displayed in the function main() in order to see that the changes have even been made.

Page 20: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

19

Program 10.1.11 #include <stdio.h> #include <conio.h> void pass_adr(int *x){ (*x)++; } void main(void){ int x=10; pass_adr(&x); printf("x=%d", x); //it is displayed x=11 getch(); }

10.1.6 Passing arrays as arguments

Passing arrays as arguments is different from passing other variables, being an exception from the usual rule of passing arguments by value [HS98]. The arrays are always passed by address without explicitly specifying this through the addressing operator &, because the name of an array is in fact the address of its first element. Therefore, a function can access and alter any element of an array received as argument. Within program 10.1.12 a single-dimensional array is passed as argument. It can be noticed that the function doubles() doesn’t receive information about the maximum dimension of the array (100), but only about the real number of elements that are processed (n, which is 10). The array is declared within main() and its elements receive initial values from 0 to 9. Within the function doubles() each element of the array doubles its value. The array is displayed on return from the function in order to see that the values of its elements are changed.

Program 10.1.12 #include <stdio.h> #include <conio.h>

Page 21: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

20

void doubles(int n, int v[]){ int i; for(i=0;i<n;i++) v[i]=v[i]*2; } void main(void){ int v[100], i; for (i=0;i<10;i++) v[i]=i; //0 1 2 3 4 5 6 7 8 9 doubles(10,v); for(i=0;i<10;i++) printf("%d ", v[i]); //0 2 4 6 8 10 12 14 16 18 getch(); }

A two-dimensional array (a matrix) is passed as argument in a similar way. Program 10.1.13 is an example of this matter. There is a difference: the function that receives the matrix as argument (modifies()) requires information regarding the maximum number of columns of the matrix (100), besides the real number of rows (n, which is 2 in this case) and of columns (m, which is 3 in this case) used by the matrix.

Program 10.1.13 #include <stdio.h> #include <conio.h> void modifies(int n, int m, int a[][100]){ int i, j; for(i=0;i<n;i++) for(j=0;j<m;j++) a[i][j]++; } void main(void){ int a[100][100]={ {1, 2, 3}, {4, 5, 6} }; int i, j;

Page 22: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

21

modifies(2, 3, a); for(i=0;i<2;i++){ for(j=0;j<3;j++) printf("%d ", a[i][j]); printf("\n"); } getch(); }

10.2 Recursion

The recursion is the process of defining an entity using the same entity [HS98]. A function is recursive if it is called directly or indirectly by itself [BK03]. One of the simplest examples of recursion is the factorial of an integer number n. It is the product of all integer numbers between 1 and n (including n) and from the mathematical point of view is written n!. For instance, 4 factorial is 4!=1x2x3x4=24.

The implementations of both recursive and iterative (non-recursive) versions are hereby presented (program 10.2.1). The function itera-tive_factorial() is very simple; it traverses the numbers between 1 and n and multiply each number i with the already calculated product of its previ-ous numbers. For the recursive version of the factorial, the function recur-sive_factorial() is called by itself. For instance, if factorial of 3 must be calculated:

! n has the initial value 3, therefore the instruction on the else branch is executed; the result will be 3 multiplied with the value returned by a new call of the function, this time with the parameter n-1, which is 2;

! n is 2, therefore the result is 2*recursive_factorial(1);

! n is 1, therefore result=1 (the true branch of the if instruction is executed) and this third call of the function ends, returning the value 1 to the second call;

! the second call of the function calculates result=2*1=2 and returns this value to the first call of the function;

Page 23: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

22

! the first call calculates result=3*2=6 and returns it where the function was initially called (in main()).

Program 10.2.1 #include <stdio.h> #include <conio.h> int iterative_factorial(int n){ int i, result=1; for(i=1;i<=n;i++) result=result*i; return result; } int recursive_factorial(int n){ int result; if(n==1) result=1; else result=n*recursive_factorial(n-1); return result; } void main(void){ int n; printf("n="); scanf("%d", &n); printf("Iterative: %d", iterative_factorial(n)); printf("\nRecursive: %d", recursive_factorial(n)); getch(); }

Generally, a recursive function has an if instruction that determines whether the last call of the function was encountered or it must be called again. Without such an instruction the functions’ calls will never end and the program will have a wrong functionality, usually within an infinite loop. In order to clarify these things, printf() instructions could be placed inside recursive functions and certain messages could be displayed this way at each call of the function.

Page 24: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

23

When a function is called by itself, memory space is allocated for a new set of automatic local variables and parameters and the function is executed from the beginning with the new set of variables. Ones a recursive call is finished and the execution of the program returns from that call of the function (with or without returned value), the local variables and the old parameters are lost and the exe-cution of the program continues from the point where the call that just ended was made [HS98].

The recursive versions of certain programs do not necessary cause improve-ments regarding the speed of execution, the dimension of a program or the memory use. Nevertheless, the recursion has several notable advantages [HS98], [BK03]:

! the code is more compact and easily written and understood than its itera-tive equivalent;

! many algorithms become clearer and simpler in their recursive implementa-tion; there are algorithms that have very difficult iterative versions;

! some problems, especially those connected to the artificial intelligence domain, have only recursive solutions;

! there are software developers who work better with the recursive version.

10.3 Solved problems

10.3.1 A real number is read and passed to a function that transforms it from Celsius to Fahrenheit and to another function that considers that it is a Fahren-heit value and transforms it to Celsius.

Program 10.3.1 #include <stdio.h> #include <conio.h> float C_F(float celsius){ return ((celsius*9)/5)+32; } float F_C(float fahrenheit){ return ((fahrenheit-32)*5)/9; }

Page 25: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

24

void main(void){ float n; printf("The number that must be transformed: "); scanf("%f", &n); printf("%.2f Celsius=%.2f Fahrenheit",n,C_F(n)); printf("\n%.2f Fahrenheit=%.2f Celsius",n,F_C(n)); getch(); }

10.3.2 The sum of two matrices (with user-defined functions). Three matrices (a, b and s) are declared within main() function. Then a function used to read the elements of a matrix is called, first for the matrix a and then for the matrix b. Those two matrices are displayed through another user-defined func-tion that is called for a and then for b. The sum of two matrices can be per-formed only if they have the same number of rows and the same number of columns respectively. If this condition is not accomplished, then an error mes-sage is displayed and the program ends. Otherwise, the function that calculates the sum is called and then the result matrix is printed. The functions that are created have the following features:

! Function read() is created to read a matrix; because it is a general func-tion it can be used to read any matrix. Its parameters are:

o n, m – the number of rows and of columns; these variables are passed by address, therefore their values are available within main() function;

o mat – the matrix that is read; it is by default passed by address;

o name – the name of the matrix that is read – a string passed as pointer.

! Function write() is created to display a matrix (any matrix). It has the following parameters:

o n, m – the number of rows and of columns; these variables are passed by value;

o mat – the matrix that is displayed;

Page 26: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

25

o name – the name of the matrix that is printed – a string passed as pointer.

! Function sum(), which calculates the sum of two matrices has the follow-ing parameters:

o n, m – the number of rows and of columns of the three matrices (this function is called only if the matrices can be added);

o m1, m2 – the matrices that are added;

o m3 – the result matrix.

The functions are very simple and familiar regarding the code. It can be noticed that the reading and the writing functions are called several times, with different parameters; this way the program benefits from the advantages of repeated use of a sequence of code described by a user-defined function. The main() func-tion also becomes very simple and clear.

Program 10.3.2 #include <stdio.h> #include <conio.h> void read(int *n, int *m, int mat[][50], char *name){ int i, j; printf("Reading - matrix %s\n", name); printf("Number of rows: "); scanf("%d", &(*n)); printf("Number of columns: "); scanf("%d", &(*m)); for(i=0;i<(*n);i++) for(j=0;j<(*m);j++){ printf("%s[%d][%d]=", name, i, j); scanf("%d", &mat[i][j]); } } void write(int n, int m, int mat[][50], char *name){ int i, j; printf("Writing - matrix %s\n", name); for(i=0;i<n;i++){ for(j=0;j<m;j++)

Page 27: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

26

printf("%3d ", mat[i][j]); printf("\n"); } } void sum (int n,int m,int m1[][50],int m2[][50],int m3[][50]){ int i, j; for(i=0;i<n;i++) for(j=0;j<m;j++) m3[i][j]=m1[i][j]+m2[i][j]; } void main(void){ int a[50][50], b[50][50], s[50][50]; int n_a, m_a, n_b, m_b; read(&n_a, &m_a, a, "a"); read(&n_b, &m_b, b, "b"); clrscr(); write(n_a, m_a, a, "a"); write(n_b, m_b, b, "b"); if((n_a!=n_b)||(m_a!=m_b)) printf("Incorrect number of rows or columns!"); else{ sum(n_a, m_a, a, b, s); write(n_a, m_a, s, "sum"); } getch(); }

10.3.3 The implementation of some mathematical expressions. The user can choose, through a repetitive menu, which expression to evaluate. Each expres-sion is implemented within a separated function. Functions receive parameters passed by value or by address (according to the context) and return a value if necessary. The program has the following menu:

1 – The surface of a square; 2 – The surface of a circle;

Page 28: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

27

3 – The surface and the height of an equilateral triangle;

0 – Exit. A while structure with an always true condition is used in order to have a repetitive menu; the while cycle is left through the function exit() that is called if the user chooses the option 0. Within the instruction while the menu is displayed and the user is asked to enter his option; these actions are per-formed by the function menu() that returns the user’s option. Then, this option is evaluated by a switch instruction and the program executes the branch that corresponds to the option.

If the user chooses option 1, then he is asked to enter the side of the square. This value is passed as argument to the function square(), which returns the surface or 0 if the side is not a positive value (from a geometrical point of view a square cannot have its side of a negative or zero value).

For option 2 the actions are performed in a similar manner; the surface of a circle is calculated (if possible). It can be noticed the use of the constant M_PI from the math.h library within the function circle().

The function triangle(), which implements option 3, is slightly more complicated because it must calculate and send back two values. The instruc-tion return cannot be used to return two separated variables. A solution is to store these values in parameters that are passed by address. Therefore, the func-tion triangle() has three parameters: the side of the triangle (passed by value) and on the other hand the surface and the height (passed by address: &s, &h). The values that are assigned to these last two parameters within the tri-angle() function are available to main() after this function is executed.

Program 10.3.3 #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <math.h> float square(float sd){ if(sd>0) return sd*sd; else return 0;

Page 29: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

28

} float circle(float r){ if(r>0) return M_PI*r*r; else return 0; } int triangle(float sd, float *s, float *h){ if(sd>0) { *s=sd*sd*sqrt(3)/4; *h=sd*sqrt(3)/2; return 1; } else return 0; } int menu(void){ int o; printf("1-Square-surface\n"); printf("2-Circle-surface\n"); printf("3-Equilateral triangle-surface, height\n"); printf("0-Exit\n"); printf("Your option: "); scanf("%d", &o); return o; } void main(void){ int option; float side, radius; float s, h; while(1){ clrscr(); option=menu(); switch(option){ case 1: printf("The side: "); scanf("%f", &side);

Page 30: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

29

s=square(side); if(s==0) printf("Error!"); else printf("Surface=%.2f",s); break; case 2: printf("The radius: "); scanf("%f", &radius); s=circle(radius); if(s==0) printf("Error!"); else printf("Surface=%.2f",s); break; case 3: printf("The side: "); scanf("%f", &side); if(triangle(side,&s,&h)==0) printf("Error!"); else{ printf("Surface=%.2f\n",s); printf("Height=%.2f",h); } break; case 0: exit(0); default: printf("Wrong option!"); } getch(); } }

10.3.4 The first n Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, …) are displayed in three versions of code. Each version is written within a separated function, and the user decides, through a menu, which version to use. The first version uses three variables: f1 with the initial value 0, f2 with the initial value 1 and f3 that is calculated as f1+f2. At the end of each iteration f1 takes the value of f2 and f2 the value of f3. The function fibo_var(), which implements this version, receives as argument the variable n and doesn’t return anything.

Page 31: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

30

The second version is probably the simple one; it stores the numbers within a single-dimensional array. The first two elements of this vector receive the initial values 0 and 1 respectively and the following elements are calculated as the sum of the previous two elements. The function fibo_arr() receives as argument the variable n and doesn’t return anything.

The third version calculates each element in a recursive way. Thus, the function fibo_rec() is called for each number that must be displayed. If n is greater than 2, then the function calls itself again.

Program 10.3.4 #include <stdio.h> #include <conio.h> #include <stdlib.h> void fibo_var(int n){ int i, f1=0, f2=1, f3; if(n==1) printf("%d ", f1); else if(n==2) printf("%d %d ", f1, f2); else{ printf("%d %d ", f1, f2); for(i=3;i<=n;i++){ f3=f1+f2; printf("%d ", f3); f1=f2; f2=f3; } } } void fibo_arr(int n){ int i, v[100]; v[0]=0; v[1]=1; for(i=2;i<n;i++) v[i]=v[i-2]+v[i-1]; for(i=0;i<n;i++) printf("%d ",v[i]);

Page 32: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

31

} int fibo_rec(int n){ if(n==1) return 0; else if(n==2) return 1; else return fibo_rec(n-1)+fibo_rec(n-2); } int menu(void){ int o; printf("1-Variables\n"); printf("2-Array\n"); printf("3-Recursion \n"); printf("0-Exit\n"); printf("Your option: "); scanf("%d", &o); return o; } void main(void){ int option, n, i; while(1){ clrscr(); do{ printf("Enter a positive number.\n"); printf("n="); scanf("%d", &n); }while(n<=0); option=menu(); switch(option){ case 1: fibo_var(n); break; case 2: fibo_arr(n); break; case 3: for(i=1;i<=n;i++) printf("%d ",fibo_rec(i)); break; case 0: exit(0); default: printf("Wrong option!"); } getch();

Page 33: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

32

} }

10.4 Questions and exercises

A. Find the error. 1. #include <stdio.h>

//and other necessary libraries void calculate(void){ //do something } void main(void){ int x; printf("x="); scanf("%d",&x); calculate(x); }

2. #include <stdio.h> void calculate(int a, int b){ x=a+b; } void main(void){ int x, a, b; printf("a="); scanf("%d",&a); printf("b="); scanf("%d",&b); calculate(a,b); printf("x=%d",x); }

3. #include <stdio.h> void calculate(int a, int b){ int c; c=a+b; return c; } void main(void){ int x, a, b; printf("a="); scanf("%d",&a); printf("b="); scanf("%d",&b); x=calculate(a,b);

Page 34: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

33

printf("x=%d",x); }

4. #include <stdio.h> int x; void calculate(void){ x=a+b; } void main(void){ int a, b; printf("a="); scanf("%d",&a); printf("b="); scanf("%d",&b); calculate(); printf("x=%d",x); }

5. #include <stdio.h> void calculate(int x){ x++; } void main(void){ int x; printf("x="); scanf("%d",&x); calculate(&x); printf("x=%d",x); }

6. #include <stdio.h> void calculate(int *a, int *b){ int aux; aux=*a; *a=*b; *b=aux; } void main(void){ int a, b; printf("a="); scanf("%d",&a); printf("b="); scanf("%d",&b); calculate(a,b); printf("a=%d, b=%d",a, b); }

Page 35: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

34

7. #include <stdio.h> void calculate(int x){ x++; } void main(void){ int x; printf("x="); scanf("%d",&x); calculate(x)=100; }

8. #include <stdio.h> int calculate(int x, int y){ return x+y; } void main(void){ int sum, a=2, b=3; sum=calculate(a+b); }

9. #include <stdio.h> int calculate(void){ int counter=0; //counts how many times the function is called counter++; return counter; } void main(void){ int i, c; for(i=1;i<=10;i++) c=calculate(); printf("Number of calls: %d",c); }

10. #include <stdio.h> int calculate(int x){ if(x==1) return 1; else return x*calculate(); } void main(void){ int i; for(i=1;i<=7;i++) printf("%d ",calculate(i)); }

Page 36: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

35

B. Considering the following programs, specify what will be printed on the screen once these programs are executed. 11. #include <stdio.h>

float calculate(int a, int b){ return a/b; } void main(void){ int a=1, b=2; printf("%.2f",calculate(a,b)); }

12. #include <stdio.h> void calculate(int x){ x++; } void main(void){ int a=1; calculate(a); printf("%d",a); }

13. #include <stdio.h> void calculate(int *x){ (*x)++; } void main(void){ int a=1; calculate(&a); printf("%d",a); }

14. #include <stdio.h> int x; void calculate(int a){ x=++a; } void main(void){ int y=1; calculate(y); printf("%d %d",x,y); }

Page 37: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

36

15. #include <stdio.h> int x; int calculate(int a){ x=++a; return a; } void main(void){ int y=1,z; z=calculate(y); printf("%d",z); }

16. #include <stdio.h> void calculate(int x, int *y){ x++; (*y)++; } void main(void){ int a=1, b=1; calculate(a,&b); printf("%d %d",a,b); }

17. #include <stdio.h> #include <conio.h> void function(void){ char c; printf("\nA letter or / to finish "); c=getch(); if(c!='/'){ function(); putch(c); } } void main(void){ function(); }

C. Choose the correct answer (one only).

18. The prototype of a function contains:

Page 38: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

37

□ a) the name of the function; □ b) the type of the returned value; □ c) the type and the name of each argument; □ d) the answers a, b and c are correct; □ e) all answers are wrong.

19. A function that has the prototype count(float mark) returns:

□ a) nothing; □ b) an int; □ c) a float; □ d) a char; □ e) a pointer.

20. A variable that is available to the entire program is called:

□ a) local; □ b) national; □ c) international; □ d) global; □ e) universal. 21. A variable that is created each time a function is called and that is de-

stroyed when the function is left is named: □ a) local; □ b) national; □ c) international; □ d) global; □ e) universal.

22. Which of the following calls of the function with the prototype int f1(void); is wrong (n is an integer)?

□ a) n=f1();; □ b) n=2*f1();; □ c) f1()=n;; □ d) printf("%d",f1());; □ e) if(f1()==n) n++;.

23. The function with the prototype void f2(int x); is considered. Which of the following calls is wrong?

□ a) f2(7);; □ b) int n=1; f2(n);; □ c) f2(3+4);; □ d) int a=1, b=2; f2(a+b);; □ e) int a=1, b=2; f2(a,b);.

24. Which of the following categories of variables don’t exist in the C pro-gramming language? □ a) local; □ b) global; □ c) static; □ d) automatic; □ e) all answers are wrong.

25. The arguments of a function can be passed by:

□ a) value; □ b) address; □ c) mail; □ d) fax; □ e) the answers a and b are correct.

D. Write programs to solve the following problems. 26. There is considered a vector of real numbers. Write a function that re-

turns the maximum value. 27. Two natural numbers are read from the keyboard. Write a function that

finds and returns the greatest common divisor of these two numbers (Euclid’s algorithm).

Page 39: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

Computer Programming – The C Language

38

28. Write a function that verifies if a number n received as argument is prime or not.

29. Perform the product of two matrices (with user defined functions). 30. Write a function that counts how many times a character c occurs with-

in a string s.

31. Three real numbers (a, b and c) are read within main() function and are passed to another function that verifies if they can be the sides of a triangle (a+b>c, a+c>b and b+c>a); the function returns 1 if the numbers can form a triangle and 0 otherwise.

32. Write a function that receives as argument a vector of real numbers, rep-resenting the coefficients of a polynomial function (f(x)=anxn+an-1xn-1+ … +a1x+a0) and a number x and returns the value of that function for the number x.

33. Write a function that receives as argument a vector of real numbers, rep-resenting the coefficients of a polynomial function (f(x)=anxn+an-1xn-1+ … +a1x+a0) and creates, in another vector, the coefficients of the func-tion’s derivative.

10.5 Answers to questions and exercises

A. 1. Function calculate() is called with parameter, but its prototype spec-ifies that it doesn’t accept parameters. 2. Variable x, which is a local variable of function main(), is not visible within function calculate(), therefore it cannot be used there (it could only be used if it would be declared). 3. Function calculate() is a void function, therefore it cannot return anything. 4. Variables a and b are local variables of function main()and cannot be used within other functions. 5. Variable x is passed by address when function cal-culate() is called, but it is not handled as a pointer by the function. 6. Func-tion calculate() works with arguments passed by address, but when the function is called these are sent by value. 7. The call of a function cannot be the left side member of an assignment. 8. Function calculate() needs two parameters, but receives only one (through the expression a+b). 9. In order to count how many times the function was called, variable counter should be declared static; otherwise it receives the initial value 0 each time the function is called. 10. The passing of the parameter is omitted when the recursive function calculate() is called by itself.

Page 40: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ACP/13_Chapter 10.pdf · 2014. 2. 21. · Conspress Publisher, Bucureúti, România, 2013 ISBN: 978-973-100-270-5 . Chapter 10

10 – User-defined functions

39

B. 11. Though function calculate() performs the action 1/2, the result is 0, because the operands are passed through integer variables; this result is returned as a float and it is displayed with two decimals, therefore 0.00. 12. Variable a has the initial value 1 and it is passed to function calculate() that increments it; because this argument is passed by value, the increment is not visible within main(), where variable a maintains its value 1, which is displayed. 13. Variable a is passed by address; for this reason the increment executed within function calculate() is performed right on the variable (not on a copy of it); therefore, the value 2 is displayed. 14. Variable x is a global variable, therefore it is available to the entire program. This variable receives, within function calculate(), the value ++1, meaning 2; this value is also visible in main(). Variable y is a local variable of function main(); the increment ++a performed on its value that was passed to function calcu-late() is not visible in main(), therefore y maintains its initial value 1. 15. Variables x and y behave as in the previous program. Variable z receives the incremented value returned by function calculate(), meaning 2. 16. Varia-ble a is passed by value, while b is passed by address; therefore, once the func-tion that increments both received values is left, a maintains its initial value 1, while b has the value 2. 17. The program displays the read characters in reverse order.

C. 18. d). 19. b). 20. d). 21. a). 22. c) – the call of a function cannot be the left side member of an assignment. 23. e) – the defined function accepts a single parameter and it is called with two parameters. 24. e) – the variables can be local or global; in turn, the local variables can be automatic (the default catego-ry) or static. 25. e).