0% found this document useful (0 votes)
5 views

Chap 6 Functions

Sure, I'll provide the answers based on the structure of your questions. ## QUESTION ONE (30 MARKS) ### a) Define the following terms: i. **Hydration (1 mark)** Hydration is the chemical reaction between cement and water, resulting in the hardening of concrete. ii. **Workability (1 mark)** Workability refers to the ease with which concrete can be mixed, placed, compacted, and finished. iii. **Segregation (1 mark)** Segregation is the separation of the coarse aggregate from the

Uploaded by

kiokocurtis
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chap 6 Functions

Sure, I'll provide the answers based on the structure of your questions. ## QUESTION ONE (30 MARKS) ### a) Define the following terms: i. **Hydration (1 mark)** Hydration is the chemical reaction between cement and water, resulting in the hardening of concrete. ii. **Workability (1 mark)** Workability refers to the ease with which concrete can be mixed, placed, compacted, and finished. iii. **Segregation (1 mark)** Segregation is the separation of the coarse aggregate from the

Uploaded by

kiokocurtis
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 51

Functions

Objectives
At the end of this chapter, the reader should be able to:

 Explain why functions are important


 Distinguish between standard library functions and user-
defined functions
 Create a function definition
 Make function calls in a program
 Pass values in function calls
 Use prototyping in function-based programs.
 Write programs that use recursive functions
Jane Kuria 07/05/24 Inoorero
University
Introduction
2

 A function is a self-contained program segment that


carries out some specific well - defined task.
 Every C program consists of one or more functions.
One of these functions must be called main. Execution
of the program will always begin by carrying out the
instructions in main.
 Additional functions will be subordinate to main, and
perhaps to one another.
 If a program contains multiple functions, their
definitions may appear in any order, though they must
be independent of one another. That is, one function
definition cannot be embedded within another.

Jane Kuria Inoorero University 07/05/24


Why use functions?
3

 The use of programmer-defined functions allows a


large program to be broken down to a number of
smaller, self-contained components.
 Each of these has some unique identifiable
purpose.
 Thus a C program can be modularized through the
intelligent use of functions.

Jane Kuria Inoorero University 07/05/24


Advantages of modularity
4

1. Elimination of code redundancy

 The repeated instructions can be placed within a single


function which can then be accessed whenever it is
needed.
 Moreover a different set of data can be transferred to
the function each time it is accessed .
 Thus the use of a function eliminates the need for
redundant programming of the same instructions.

Jane Kuria Inoorero University 07/05/24


2. Clear program logic
5

 Equally important is the logical clarity resulting from the


decomposition of a program into several concise functions where
each function represents some well-defined part of the overall
problem.

 Such programs are easier to write and debug and their logical
structure is more clear than programs which lack this type of
structure. This is especially true of lengthy, complicated programs.

 Most C programs are therefore modularized in this manner, even


though they may not involve repeated execution of some task.

 In fact the decomposition of a program into individual program


modules is generally considered to be good programming practice.

Jane Kuria Inoorero University 07/05/24


3. Program libraries
6

 This use of functions also enables a programmer to


build a customized library of frequently used routines
or of routines containing system-dependent features.
 Each routine can be programmed as a separate function
and stored within a special library file.
 If a program requires a particular routine, the
corresponding library function can be accessed and
attached to the program during the compilation
process.
 Hence a single function can be utilized by many
different programs.
Jane Kuria Inoorero University 07/05/24
Types of functions
7

 Functions can be classified into two:

 Standard library functions and


 User defined functions.

Jane Kuria Inoorero University 07/05/24


Standard library functions
8

 Every compiler comes with some standard predefined


functions which are available for your use.
 These are mostly input/output functions, character and
string manipulation functions, and math functions.
 Prototypes are defined for you by the compiler writer
for all of the functions that are included with your
compiler.
 A few minutes spent studying your compiler’s
Reference Guide will give you an insight into where
the prototypes are defined for each of the functions.
Jane Kuria Inoorero University 07/05/24
Standard library functions
9

 In addition, most compilers have additional functions


predefined that are not standard but allow the programmer
to get the most out of a particular computer.
 One example of a library of this type is the CONIO library
which is provided as part of the Turbo C package.
 The CONIO library provides functions that allow you to
position output on the monitor, change the color of text
written to the monitor and a number of other screen
(console) based operations.
 Most of these libraries can be used using the #include
statement

Jane Kuria Inoorero University 07/05/24


User – defined functions
10

 This is a function created and customized by a


programmer for use within a given program.

Jane Kuria Inoorero University 07/05/24


Defining a function
11

 The general form of a C function is:


 type function_name(parameter- list)


 {
 statements
 }
 type specifies the return type of a function. A function can return any type
of data.
 If no data type specifier is present, the C compiler assumes that the
function is returning an integer.
 In other words int is the default type when no type specifier is present.
 However, when a function returns a type other than int, it must be
explicitly declared.

Jane Kuria Inoorero University 07/05/24


Example: function returns a
12
double.
 /* Compute the area of a rectangle */
 double rect_area(double side1, double side 2)
 {
 return(side1*side2);

 }
 function_name represents any meaningful
descriptive tag you will assign to the function for
example rect_area above.

Jane Kuria Inoorero University 07/05/24


Parameter lists
13

 parameter-list represents the variables used in the


function body (if any).
 If more than one, they are listed inside the
parenthesis with each parameter (also known as an
argument) preceded by its data type as it is done
in a declaration statement.
 Hence in the previous example, side1 and side2
are the parameters of the rect_area function.

Jane Kuria Inoorero University 07/05/24


Statements
14

 statements is the sequence of statements that make


up the function body.
 If the function is expected to return some value,
the sequence will have a return statement
(discussed shortly), otherwise (void type functions),
there wont be any need for a return statement.

Jane Kuria Inoorero University 07/05/24


Arguments
15

 The arguments are called formal arguments because


they represent the names of data items that are
transferred into the function from the calling portion of
the program.
 They are also known as parameters or formal
parameters.
 The corresponding arguments in the function reference
are called actual arguments since they define the data
items that are actually transferred).
 Each formal argument must be of the same data type as
the data item it receives from the calling portion of the
program.

Jane Kuria Inoorero University 07/05/24


Return statements
16

 Information is returned from the function to the calling


portion of the program via a return statement.
 The return statement also causes the program logic to return
to the point from which the function was accessed.

 In general terms the return statement is written as:


 return (expression);

 Only one expression can be included in the return


statement. Thus, a function can return only one value to the
calling portion via return.

Jane Kuria Inoorero University 07/05/24


Example : Factorial of an integer n
17

 The factorial of a positive integer quantity n is


defined as n! = 1 * 2 * 3 *…….* (n - 1) * n.
 Thus, 2! = 1 * 2 = 2; 3! = 1 * 2 * 3 = 6; 4! = 1 * 2 *
3 * 4 = 24; and so on.

 The function shown below calculates the functional


of a given positive integer n. The factorial is
returned as a long integer quantity, since factorials
grow in magnitude very rapidly as n increases.
Jane Kuria Inoorero University 07/05/24
Example..
18

1. long int factorial (int n) /*Calculate the factorial of n


*/
2. {
3. int i;
4. long int prod = 1;
5. if (n >1 )
6. for(i =2; i <=n; i++)
7. prod * = i; /* prod=prod*I; */
8. return(prod);
9. }

Jane Kuria Inoorero University 07/05/24


Example..
19

 Notice the long int specification that is included in the first line of
the function definition. The local variable prod is declared to be a
long integer within the function.
 It is assigned an initial value of 1 though its value is recalculated
within a for loop. The final value of prod which is returned by the
function represents the desired value of n factorial (n!).
 If the data type specified in the first line is inconsistent with the
expression appearing in the return statement, the compiler will
attempt to convert the quantity represented by the expression to the
data type specified in the first line.
 This could result in a compilation error or it may involve a partial
loss in data (due to truncation). Inconsistency of this type should be
avoided at all costs.

Jane Kuria Inoorero University 07/05/24


Using void
20

 The keyword void can be used as a type specifier when


defining a function that does not return anything or
when the function definition does not include any
arguments.
 The presence of this keyword is not mandatory but it is
good programming practice to make use of this feature.

 Consider a function that accepts two integer quantities,


determines the larger of the two and displays it (the
larger one).
 This function does not return anything to the calling
portion. Therefore the function can be written as;
Jane Kuria Inoorero University 07/05/24
Example
21

1. void maximum (int x, int y)


2. {
3. int z;
4. z = (x >= y)? x : y;
5. printf(“\n \n maximum value = %d ” , z),
6. }

Jane Kuria Inoorero University 07/05/24


Accessing a function
22

 A function can be accessed by specifying its name


followed by a list of arguments enclosed in
parenthesis and separated by commas.
 If the function call does not require any arguments
an empty pair of parenthesis must follow the name
of the function.
 The function call may be part of a simple
expression (such as an assignment statement), or it
may be one of the operands within an expression.

Jane Kuria Inoorero University 07/05/24


Actual arguments
23

 The arguments appearing in the function call are


referred to as actual arguments in contrast to the
formal arguments that appear in the first line of the
function definition. (They are also known as actual
parameters or arguments).
 In a normal function call, there will be one actual
argument for each formal argument. Each actual
argument must be of the same data type as its
corresponding formal argument.
 Remember that it is the value of each actual argument
that is transferred into the function and assigned into
the corresponding formal argument.

Jane Kuria Inoorero University 07/05/24


Function calls
24

 There may be several different calls to the same


function from various places within a program.
 The actual arguments may differ from one function call
to another.
 Within each function call however the actual
arguments must correspond to the formal arguments in
the functions definition; i.e. the number of actual
arguments must be the same as the number of formal
arguments and each actual argument must be of the
same data type as its corresponding formal argument.
Jane Kuria Inoorero University 07/05/24
Example: Determining the maximum
25
of two integers (Complete program)
 The following program determines the largest of
three integers quantities. The program makes use of
a function that determines the larger of two integer
quantities.
 The overall strategy is to determine the larger of
the first two quantities and then compare the value
with the third quantity. The largest quantity is then
displayed by the main part of the program.

Jane Kuria Inoorero University 07/05/24


Example..
26

 /*Determine the largest of the three integer quantities*/


1. #include<stdio.h>
2. int maximum (int x, int y) /*Determine the larger of
two quantities*/
3. {
4. int z;
5. z = (x > = y )? x : y;
6. return(z);
7. }

Jane Kuria Inoorero University 07/05/24


Example continued
27

1. main()
2. {
3. int a , b , c ,d;
4. /*read the integer quantities*/
5. printf(“\n a = ”);
6. scanf(“%d”, &a);
7. printf(“\n b = ” );
8. scanf(“%d”, &b);
9. printf(“\n c = ”);
10. scanf(“%d”, &c);
11. /* Calculate and display the maximum value */
12. d = maximum (a, b);
13. printf (“\n \n maximum = % d ”, maximum (c ,d));
14. return 0;
15. }

Jane Kuria Inoorero University 07/05/24


Explanation
28

 The function maximum is accessed from two different


places in main. In the first call to maximum, the actual
arguments are the variables a and b whereas in the
second call, the arguments are c and d. (d is a temporary
variable representing the maximum value of a and b).

 Note the two statements in main that access maximum,


i.e.

 d = maximum (a, b);


 printf(“ \n \n maximum = %d ”, maximum (c, d));

Jane Kuria Inoorero University 07/05/24


Explanation
29

 A single statement can replace these two statements, for example:


 printf (“ \n\n maximum = %d ” maximum(c, maximum (a, b)));


 In this statement, we see that one of the calls to maximum is an


argument for the other call.
 Thus the calls are embedded one within the other and the
intermediary variable d is not required.
 Such embedded functions calls are permissible though their logic
may be unclear.
 Hence they should generally be avoided by beginning
programmers.

Jane Kuria Inoorero University 07/05/24


Function prototypes
30

 A prototype is a model (or representation) of the real


thing.

 All functions in a main program must be prototyped if


their code definition appears after the main function.
 While a programmer is free to place function code
definitions for functions used in the main program
before the main program (see the previous example),
programmers prefer a top down approach in which
main appears ahead of the programmer-defined
function definition.
Jane Kuria Inoorero University 07/05/24
Function prototypes
31

 In such a situation, the function call (within main) will


precede the function definition. This can be confusing to the
compiler unless the compiler is first alerted to the fact that
the function being accessed will be defined later in the
program. A function prototype is used for this purpose.

 Function prototypes are usually written at the beginning of


a program ahead of any programmer-defined function
(including main) The general form of a function prototype
is;

 type function-name (parameter-list);


Jane Kuria Inoorero University 07/05/24
Function prototypes....
32

 Where type represents the type of the item that is


returned by the function, function-name represents
the name of the function, parameter-list represents
the types and names of the arguments used in
executing the function.
 For example, the statement void square(int
number); is a prototype for the function square
 Note that a function prototype resembles the first
line of a function definition (although a definition
prototype ends with a semicolon).

Jane Kuria Inoorero University 07/05/24


Function prototypes....
33

 The names of the argument(s) can be omitted (though it is not a good idea
to do so). However the arguments data types are essential.

 Hence, the prototype for the function square may also be written as void
square(int);

 Although function prototypes are not mandatory in C, they are however


desirable because they facilitate error checking between the calls to a
function and the corresponding function definition.

 Since a prototype is a model of a function, the compiler uses it to check


each of your calls to the function and determine if you have used the
correct number of arguments in the function call and if they are of the
correct type.

Jane Kuria Inoorero University 07/05/24


Example: Factorial of an integer n
34

 /*Calculate the factorial of an integer quantity*/


1. #include<stdio.h>
2. long int factorial (int n);
3. main()
4. {
5. int n;
6. /* read in the integer quantity */
7. printf (“\n n = “);
8. scanf (“%d “, &n);
9. /* Calculate and display the factorial*/
10. printf (“\n n =%\d”, factorial (n));
11. return 0;
12. }

Jane Kuria Inoorero University 07/05/24


Example
35

 /*Calculate the factorial of n*/


1. long int factorial (int n)
2. {
3. int i;
4. long int prod=1;
5. if (n >1)
6. for( i=2; i<=n; i ++)
7. prod *= i;
8. return (prod);
9. }

Jane Kuria Inoorero University 07/05/24


Recursion
36

 Recursion is the process by which a function calls itself


repeatedly until a special condition is satisfied.

 For a problem to be solved using recursion, two conditions


must be satisfied. These are:

 The solution must be written in a recursive form i.e. it


should be possible to express the solution in form of itself.

 There must be a stopping case or a simple solution. This is


the terminating condition.
Jane Kuria Inoorero University 07/05/24
Recursion
37

 We reuse the factorial function to illustrate this.


 The factorial of any possible integer can be expressed as;


 n ! =n * (n-1) * (n-2) *………* 1.
 e.g. 5 ! = 5 * 4 * 3 * 2 * 1.

 However we can rewrite the expression as; 5! = 5 * 4!


 Or generally,

 n! = n * (n –1)! (Recursive statement)


 This is to say that in the factorial example, the calculation of n is expressed in form of a
previous result (condition (i) is satisfied).

 Secondly 1! = 1 by definition, therefore condition (ii) is satisfied i.e. a stopping case.

Jane Kuria Inoorero University 07/05/24


Example: Using the factorial
38
function in recursive form.
1. #include<stdio.h>
2. long int factorial (int n); /*factorial function prototype*/
3. main()
4. {
5. int n;
6. /*Read in the integer quantity*/
7. printf (“n = ” );
8. scanf (“%d ”, &n);
9. /*Calculate and display the factorial*/
10. printf (“n! =%d \n”, factorial (n));
11. return 0;
12. }

Jane Kuria Inoorero University 07/05/24


Example
39

 /* Function definition */
1. long int factorial (int n)
2. {
3. if (n <=1) /*terminating condition*/
4. return (1);
5. else
6. return (n * factorial (n-1));
7. }

 The functional factorial calls itself recursively with an actual


argument that decreases in magnitude for each successive call. The
recursive call terminates when the value of the actual argument
becomes equal to 1.

Jane Kuria Inoorero University 07/05/24


Example a)
40

1. #include<stdio.h>
2.

3. /* define the prototype for the function used in this program. */


4. void count_dn(int count);
5. void main()
6. {
7. int index;
8. index = 8;
9. count_dn(index);
10. }

Jane Kuria Inoorero University 07/05/24


Example b)
41

 /* -- Function definition -------------------- */


1. void count_dn(int count)
2. {
3. count--;
4. printf("The value of the count is %d\
n",count);
5. if(count > 0)
6. count_dn(count);
7. printf("Now the count is %d\n",count);
8. }

Jane Kuria Inoorero University 07/05/24


Output
42

Jane Kuria Inoorero University 07/05/24


Explanation
43

 In this program the variable index is set to 8, and is


used as the argument to the function count_dn. The
function simply decrements the variable, prints it
out in a message, and if the variable is not zero, it
calls itself, where it decrements it again, prints it,
etc. etc. etc.
 Finally, the variable will reach zero, and the
function will not call itself again. Instead, it will
return to the prior time it called itself, and return
again, until finally it will return to the main
program.
Jane Kuria Inoorero University 07/05/24
Explanation
44

 For purposes of understanding you can think of it


as having 8 copies of the function count_dn
available and it simply called all of them one at a
time, keeping track of which copy it was in at any
given time.

Jane Kuria Inoorero University 07/05/24


Example
45

1. #include <stdio.h>
2. void recurse(int i);
3. void main()
4. {
5. recurse(0);
6. }
7.

8. /* -- Function definition -------------------- */


9. void recurse(int i)
10. {
11. if(i<10)
12. {
13. printf(“%d ”, i);
14. recurse(i+1);
15. }
16. }

Jane Kuria Inoorero University 07/05/24


Output
46

Jane Kuria Inoorero University 07/05/24


Output
47

 The recurse( ) function is first called with 0. This is


recurse’s( ) first activation.
 Since 0 is less than 10, it is printed. After printing
it, the function is called again with (i+1), i.e. 1.
 The process repeats until recurse( ) is called with
the value 10.
 Therefore the numbers are printed in ascending
order from 0 to 9.

Jane Kuria Inoorero University 07/05/24


Exercises
48

1. Explain the meaning of each of the following


function prototypes
 int f(int a);
 void f(long a, short b, unsigned c);
 char f(void);

2. Each of the following is the first line of a function


definition. Explain the meaning of each.
 float f(float a, float b)
 long f(long a)

Jane Kuria Inoorero University 07/05/24


Exercises
49
3. Describe the output generated by the followed program.

 #include<stdio.h>
 int func(int count);
 main()
 {
 int a,count;
 for (count=1; count< = 10; count + +)
 {
 a = func(count);
 printf(“%d”,a);
 }
 return 0;
 }
 int func(int x)
 {
 int y;
 y = x * x;
 return(y);
 }

Jane Kuria Inoorero University 07/05/24


Exercises
50

 4. Write a program that creates a function, called avg() that


reads ten floating-point numbers entered by the user and
returns their average.

 5. Write a program that uses a function called hypot() that


returns the length of the hypotenuse of a right angled
triangle when passed the length of the two opposing sides.
Have the function return a double value. The type of the
parameters must be double as well Demonstrate the function
in a program. (The Pythagorean theorem states that the sum
of the squares of the two opposing sides equals the two
opposing sides equals the square of the hypotenuse).

Jane Kuria Inoorero University 07/05/24


Exercises
51

 6. The Future Value (fv) earned from an investment amount (p), at a


constant interest rate (r), over n years is calculated using the formula:

 fv = p * 1
 (1 + r)n

 Required:
 Write a program that reads the investment amount, rate and number of
years, calculates and prints the future value.

 Hint: Implement this program using a function getfv( ), which accepts


three parameters (p, r and n), calculates the fv and returns the value of fv.

Jane Kuria Inoorero University 07/05/24

You might also like