Functions and Recursion
Functions and Recursion
Lab-sheet 6
Functions & Recursion
Functions break large computing tasks into smaller ones, and enable people to build on what
others have done instead of starting over from scratch. C program may consist of several small
functions. A program may reside in one or more source files. Source files may be compiled
separately and loaded together, along with previously compiled functions from libraries.
Note:
1. All parts except function-name and () are non-mandatory.
2. If return type is omitted, int is assumed (will give warning).
3. Function may not be declared before use (in C89/90). However, a prototype declaration is
must for C99. However, it is always a best practice to declare a function before use, so as to
perform a strict type-checking. A prototype declaration is terminated by a semi-colon(;). 4. All
automatic and register variables must be initialized within a function.
➢ A function is called by its name followed by a list of argument which must match the
Parameter passing:
➢ A Parameter is the symbolic name for "data" that goes into a function. There are two ways to
pass parameters in C: (i) Pass by Value, (ii) Pass by Reference.
(i) Pass by Value: pass by Value, means that a copy of the data is made and stored by way
of the name of the parameter. Any changes to the parameter have NO effect on data in
the calling function.
(ii) Pass by Reference: a reference parameter "refers" to the original data in the calling
function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL
variable. Reference to a variable may be passed using ampersand operator (&) function-
name(¶m1, ¶m2,… )
The ampersand (&) is the syntax to tell C that any changes made to the parameter also
modify the original variable containing the data.
➢ Recursion: C functions may be used recursively; that is a function may call itself either
directly or indirectly. When a function calls itself recursively, each invocation gets a fresh set
of all the automatic variables, independent of the previous set. Recursion may provide no
saving in storage, since somewhere a stack of the values being processed must be
maintained. Nor will it be faster.
➢ The C Preprocessor: C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation. All preprocessor
commands begin with a hash symbol (#)
Programs:
1. Write a C program that takes an integer number as a parameter and returns the reverse of
it. Use the following function in your program