Chapter 7 Functions
Chapter 7 Functions
Chapter 7
1
Preliminaries
Library functions: which are used to carry out a
number of commonly used operations or
calculations.
C also allows programmers to define their own
functions for carrying out various individual tasks.
This are also called user defined functions.
The use of programmer-defined functions allows a
large program to be broken down into a number of
smaller, self-contained components, each of which
has some unique, identifiable purpose.
Thus a C program can be modularized through
the intelligent use of such functions.
2
Contd…
There are several advantages to this modular
approach to program development.
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 avoids the need for
redundant (repeated) programming of the
same instructions.
Equally important is the logical clarity resulting
from the decomposition of a program into several
concise
3 functions, where each function represents
Contd…
Such programs are easier to write and easier
to debug, and their logical structure is more
apparent than programs which lack this type
of structure.
The use of functions also enables a
programmer to build a customized library of
frequently used routines or of routines
containing system-dependent features.
It also promotes portability since programs
can be written that are independent of
system-dependent features.
4
Function Overview
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
5
another.
Contd…
Generally, a function will process information
that is passed to it from the calling portion
of the program,
and return a single value.
Information is passed to the function via special
identifiers called arguments (also called
parameters), and returned via the return
statement.
Some functions, however, accept information but
do not return anything (as, for example, the
library function printf ) , whereas other functions
(e.g., the library function pow) return multiple
values.
6
Lowercase to Uppercase Character
Conversion
7
DEFINING A FUNCTION
In general terms, the first line can be written as
data- type name( type1 arg1, type2
arg2, . . ., typen argn)
An empty pair of parentheses must follow the
function name if the function definition does
not include any arguments.
The data types are assumed to be of type int if
they are not shown explicitly.
However, the omission of the data types is
considered poor programming practice, even if
the data items are integers.
8
Contd…
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. Some textbooks refer to actual
arguments simply as arguments, or as actual parameters.
The identifiers used as formal arguments are "local" in the
sense that they are not recognized outside of the function.
Hence, the names of the formal arguments need not be the
same as the names of the actual arguments in the calling
portion of the program.
Each formal argument must be of the same data type of
actual argument, however, as the data item it receives
from the calling portion of the program.
9
Contd…
The remainder of the function definition is a
compound statement that defines the action to
be taken by the function.
This compound statement is sometimes
referred to as the body of the function.
Like any other compound statement, this
statement can contain expression statements,
other compound statements, control
statements, and so on. It should include one or
more return statements, in order to return a
value to the calling portion of the program.
A function can access other functions. In fact, it
can even access itself (this process is known as
recursion)
10
Contd…
A function definition can include multiple
return statements, each containing a different
expression.
Functions that include multiple branches often
require multiple returns.
11
Contd…
If a function reaches the end without encountering a
return statement, control simply reverts back to the
calling portion of the program without returning any
information.
The presence of an empty return statement (without the
accompanying expression) is recommended in such
situations, to clarify the logic and to accommodate
future modifications to the function.
12
Factorial Function
13
Contd…
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 of data (e.g., due to truncation). In any event,
inconsistencies of this type should be avoided.
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.
14
Example
15
ACCESSING A FUNCTION
A function can be accessed (i.e., called) by specifying its
name, followed by a list of arguments enclosed in
parentheses and separated by commas.
If the function call does not require any arguments, an empty
pair of parentheses must follow the name of the function.
The function call may be a part of a simple expression(such
as an assignment statement), or it may be one of the
operands within a more complex expression.
The actual arguments may be expressed as constants, single
variables, or more complex expressions.
However, each actual argument must be of the same data
type as its corresponding formal argument.
If the function returns a value, the function access is often
written as an assignment statement; e.g., y =
polynomial(x);
This function access causes the value returned by the
function to be assigned to the variable y.
On the other hand, if the function does not return anything,
the function access appears by itself; e.g., display(a, b, c);
16
Largest of Three Integer Quantities
17
Contd…
18
FUNCTION PROTOTYPES
The programmer-defined function may preceded main.
Thus, when these programs are compiled, the programmer-
defined function will have been defined before the first
function access.
However, many programmers prefer a "top-down" approach,
in which main appears ahead of the programmer-defined
function definition.
In such situations the function access (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 Finction prototype is used for this purpose.
Function prototypes are usually written at the beginning of a
program, ahead of any programmer-defined functions
(including main).
The general form of a function prototype is
data-type name( type I arg I , type 2 arg 2, . . ., type n
arg n );
19
Contd…
20
21
Simulation of a Game of Chance (Shooting
Craps)
Simulation of a Game of Chance (Shooting Craps)
Here is an interesting programming problem that includes
multiple function calls at several different levels. Both
library functions and programmer-defined functions are
required.
Craps is a popular dice game in which you throw a pair of
dice one or more times until you either win or lose.
The game can be simulated on a computer by generating
random numbers rather than actually throwing the dice.
You can throw the dice once and obtain a score of either 7
or 11; or you can obtain a 4, 5, 6, 8, 9 or 10 on the first
throw and then repeat the same score on a subsequent
throw before obtaining a 7.
Conversely, there are two ways to lose. You can throw the
dice once and obtain a 2,3 or 12; or you can obtain a 4,
5,6,
22 8, 9 or 10 on the first throw and then obtain a 7 on a
subsequent throw before repeating your original score.
PASSING ARGUMENTS TO A FUNCTION
When a single value is passed to a function via an
actual argument, the value of the actual argument
is copied into the function.
Therefore, the value of the corresponding formal
argument can be altered within the function, but
the value of the actual argument within the calling
routine will not change.
This procedure for passing the value of an
argument to a function is known as passing by
value.
23
Pass by Value
24
Contd…
Passing an argument by value has advantages and
disadvantages. On the plus side, it allows a single
valued actual argument to be written as an
expression rather than being restricted to a single
variable.
Moreover, if the actual argument is expressed
simply as a single variable, it protects the value of
this variable from alterations within the function.
On the other hand, it does not allow information to
be transferred back to the calling portion of the
program via arguments. Thus, passing by value is
restricted to a one-way transfer of in formation.
25
Pass by Reference
We can pass the memory reference to the
called function using arrays or pointers.
This is called the pass by reference.
This allows the program to alter the value of
formal argument from the called function.
This also allows the two way information
transfer.
26
RECURSION
Recursion is a process by which a bction calls
itself repeatedly, until some specified condition
has beensatisfied.
The process is used for repetitive computations in
which each action is stated in terms of a previous
result.
Many iterative (i.e., repetitive) problems can be
written in this form.
In order to solve a problem recursively, two
conditions must be satisfied.
First, the problem must be written in a recursive
form.
And second, the problem statement must include
a stopping condition.
27
Contd…
28
Main Logic in Recursive functions
If a recursive function contains local variables,
a deferent set of local variables will be
created during each call. The names of the
local variables will, of course, always be the
same, as declared within the function.
However, the variables will represent a
different set of values each time the function
is executed.
Each set of values will be stored on the stack,
so that they will be available as the recursive
process“unwinds,” i.e., as the various function
calls are “popped” off the stack and executed.
29
Printing Backwards
EXAMPLE 7.15 Printing Backwards The
following program reads in a line of text on a
character-by-character basis, and then displays the
characters in reverse order. The program utilizes
recursion to carry out the reversal of the
characters.
30
31
The Towers of Hanoi
The Towers of Hanoi is a well-known children's
game, played with three poles and a number of
different-sized disks. Each disk has a hole in the
center, allowing it to be stacked around any of the
poles. Initially, the disks are stacked on the
leftmost pole in the order of decreasing size, i.e.,
the largest on the bottom and the smallest on the
top.
33
Contd…
34
Contd…
35
Input and Output
36
Thank You!!!!
37