PSPC Chapter 4
PSPC Chapter 4
FUNCTIONS
TOPICS
Functions:
Designing structured programs
Function Basics,
User Defined Functions,
a) Function prototype/function declaration
b) Function definition
c) Function call
d) Function parameters
e) return statement
Parameter passing mechanism
a) call by value
b) call by reference
Categories of functions
Category 1: Functions with no arguments and no return value.
Category 2: Functions with arguments and no return value.
Category 3: Functions with arguments and return value.
Category 4: Functions with no arguments and return value.
Local variables, global variables, static variables
Scope of variables
a) Block scope
b) Function scope
c) Program scope
d) File scope
Storage classes
a)auto
b)register
c)extern
d)static
Recursion- Recursive Functions
Inter Function Communication
1D array for inter function communication
(a)passing individual elements
i)passing data values
ii)passing addresses
(a)passing entire array
2D array for inter function communication
a)passing individual elements
b)passing a row
c)passing entire 2D array
Standard functions
Preprocessor Commands.
Designing Structured Programs in C
Disadvantages :
1.Time take to jump the control between functions (considerable compared to development
efforts )
2. If programmer is not expert in using recursive functions, there is a chance raising stack over
flow exception.
1. Built-in functions:
Built in functions are the functions that are provided by the C library. Many activities
in C are carried out using library functions. These functions perform file access,
mathematical computations, graphics, memory management etc.
A library function is accessed simply by writing the function name, followed by an
optional list of arguments and header file of used function should be included with the
program
Definition of built in functions are defined in a special header file. A header file can
contain definition of more than one library function but the same function can not be
defined in two header files.
These are from C-Library files (header files). Eg: printf(), scanf(), strcpy(), strlwr(),
strcmp(), strlen(), strcat(), gets(), puts(), getchar(), putchar() etc
The general format for declaring a function that accepts some arguments and returns some
value as a result can be given as:
Here function_name is valid name for the function. return_type specifies the data type of the
value that will be returned to the calling function.
b) Function definition:
A function definition describes how the function computes the value it returns. A function
definition consists of a function header followed by a function body. The syntax of a function
header followed by a function body.
The syntax of a function definition can be given as
return_type function_name(data_type variable1,data_type variable2...)
{
==========;
statements;
==========;
==========;
return(variable);
}
The body of the function enclosed in braces. ‘C’ allows the definition to be placed if the
function is defined before its calling then its prototype declaration is optional. Parameter list is
the list of formal parameters that the function receives. Return type is the datatype the function
returns. In a function every statement should be terminated with semicolon ( ; )
c) Function call:
The function call statement invokes the function. When a function is invoked, the compiler
jumps to the called function to execute the statements that are a part of the function. Once the
called function is executed, the program control passes back to the calling function.
function_name(variable1,variable2,....);
When the function declaration is present before the function call, the compiler can check if the
correct number and type of arguments are used in the function call and the returned value, if
any, is being used reasonably.
d) Function parameter:
Function parameters are may be classified under two groups, actual and formal arguments or
parameters.
The parameters specified in the function call are known as actual parameters and those
specified in the function declaration are known as formal parameters.
e) return statement:
The return statement is used to terminate the execution of a function and returns control to the
calling function.
A return statement may or may not return a value to the calling function. The syntax of
return statement can be given as
return<expression>;
a) Actual arguments:
An actual argument is a variable or an expression contained in a function call that replaces the
formal parameter which is a part of the function declaration.
Sometimes, a function may be called by a portion of a program with some parameters and
these parameters are known as the actual arguments.
For example:
b) Formal arguments:
Formal arguments are the parameters present in a function definition which may also be called
as dummy arguments or the parametric variables. When the fuction is invoked, the formal
parameters are replaced by the actual parameters.
PARAMETER PASSING TECHNIQUES IN C:
The parameter passing mechanism refers to the actions taken regarding the parameters when a
function is invoked. There are two parameter passing techniques are available in C. They are
1) Call by value
2) Call by Reference
1) Call by value:
Whenever a portion of the program invokes a function with formal arguments, control
will be transferred from the main to the calling function and the value of the actual
argument is copied to the function.
Within the function, the actual value copied from the calling portion of the program
may be altered (or) changed.
When the control is transfered back from the function to the calling portion of the
program, the altered values are not transfered back.
This type of passing formal arguments to a function is technically known as “call by
value”.
Example: A program to exchange the contents of two variables using a call by value.
Output:
2) Call by Reference:
When a function is called by a portion of a program, the address of the actual
arguments are copied onto the formal arguments, though they may be referred by
different variable names.
The content of the variables that are altered within the function block are returned to
the calling portion of a program in the altered form itself, as the formal and the actual
arguments are referencing the same memory location (or) address.
This is technically known as call by reference (or) call by address.
Example:
A program to exchange the contents of two variables using a call by reference
Output:
Category of functions:
A function, depending on whether arguments are present (or) not and whether a value is
returned (or) not, may belong to one of the following categories.
Category 1: Functions with no arguments and no return value.
Category 2: Functions with arguments and no return value.
Category 3: Functions with arguments and return value.
Category 4: Functions with no arguments and return value.
Example:
Output:
Output:
Output:
Example:
Output:
TYPES OF VARIABLES
IMPORTANT POINTS:
Common property:
• The memory space used for these kinds of variables are allocated
(reserved) using language constructs.
1. Local variables
2. Parameter variables
Common property:
The integer variables are defined within a function block of the funct(). Local variables are
referred only the particular part of a block (or) a function.
Global variables:
Global variables are variables defined outside the main function block.
These variables are referred by the same data type and by the same name through out
the program in both the calling portion of a program and in the function block.
Example:
static variable
static variables are declared by writing keyword static in front of the declaration. If a static
variable is not initialized then it is automatically initialized to 0.
A static variable is initialized only once and its value is retained between function calls.
Program:
Output:
Here b is a static variable. First time when the function is called b is initialized to 10. Inside
the function, value of b becomes 11. This value is retained and when next time the function is
called, value of b is 11 and the initialization is neglected. Similarly when third time function is
called, value of b is 12. Note that the variable a, which is not static is initialized on each call
and its value is not retained.
SCOPE OF VARIABLES
In C, all constants and variables have a defined scope. By scope we mean the accessibility and
visibility of the variables at different points in the program. A variable or a constant in C has
four types of scope:
1. Block scope
2. Function scope
3. Program scope
4. File scope
1. Block scope:
We know that a statement block is a group of statements enclosed within opening and closing
braces{}. If a variable is declared within a statement block then, as soon as the control exists
that block, the variable will cease to exist. Such as variable, also known as a local variable, is
said to have a block scope.
For example, if we declare an integer x inside a function, then that variable is unknown
to the rest of the program(i.e., outside that function).
Example:
Output:
2. Function scope:
Function scope indicates that a variable is active and visible from the beginning to the end of a
function. In C, only the goto label has function scope. In other words function scope is
applicable only with goto label names. This means that the programmer cannot have the same
label name inside a function.
3. Program scope:
Local variables(also known as internal variables) are automatically created when they are
declared in the function and are usable only within that function. The local variables are
unknown to other functions in the program. Such variables cease to exist after the last
statement in the function in which they are declared and re-created each time the function is
called.
However, if we want this function to access some variables which are not passed to them as
arguments, then declare those variables outside any function blocks. Such variables are
commonly known as global variables and can be accessed from any point in the program.
Example:
Output:
4. File scope:
When a global variable is accessible until the end of the file, the variable is said to have file
scope. To allow a variable to have file scope, declare that variable with the static keyword
before specifying its data type,as shown:
A global static variable can be used anywhere from the file in which it is declared but it is not
accessible by any other files. Such variables are useful when the programmer writes his/her
own header files.
Storage classes in C
In addition to data type, each variable has one more attribute known as storage class. The
proper use of storage classes makes our program efficient and fast. In larger multifile
programs, the knowledge of storage classes is indispensable. We can specify a storage class
while declaring a variable.
When the storage class specifier is not present in the declaration, compiler assumes a default
storage class based on the place of declaration.
1. Automatic variables:
All the variables declared inside a block/ function without any storage class specifier
are called automatic variables.
We may also use the keyword auto to declare automatic variables, although this is
generally notbdone.
The uninitialized automatic variables initially contain garbage value.
The scope of these varaibles is inside the function or block in which they are declared
and they cant be used in any other function/block.
They are named automatic since storage for them is reserved automatically each time
when the control enters the function/block and are released automatically when the
function/block terminates.
The features of a variable defined to have on automatic storage class are
Storage Primary memory of computer
Default initial value Garbage value
Scope Local to the block in which the variable is defined
Life time Till the control remains within the block in which the variable is
defined
Example 1:
Output:
Here when the function func() is called first time, the variables x and y are created and
initialized, and when the control returns to main(), these variables are destroyed.
When the function func() is called for the second time, again these variables are created and
initialized, and are destroyed after execution of the function.
So automatic variables come into existence each time the function is executed and are
destroyed when the function terminates.
Since automatic variables are known inside a function or block only, so we can have variables
of same name in different functions or blocks without any conflict.
For example in the following program the variable x is used in different blocks (here blocks
consist of function body) without any conflict.
Example 2:
Output:
Here the variable x declared inside main() is different from the variable x declared inside the
function func().
2. Register variables:
Register storage class can be applied only to local variables.
The scope, lifetime and initial value of register variables are same as that of automatic
variables.The only difference between the two is in the place where they are stored.
Automatic variables are stored in memory while register variables are stored in CPU
registers.
Registers are small storage units present in the processor.
The variables stored in registers can be accessed much faster than the variables
stored in memory. So the variables that are frequently used can be assigned register
storage class for faster processing.
For example the variables used as loop counters may be declared as register variables
since they are frequently used.
Register storage class declaration is applicable only to int,char, and pointer data type.
Ex:
register int a;
Example 1:
Output:
Example 2:
Output:
gcc register1.c
./a.out
1 2 3 4 5 6 7 8 9 10 11 12
13 14 15
3. External variables:
The variables that have to be used by many functions and different files can be
declared as external variables.
The initial value of an uninitialized external variable is 0.
The declaration of an external variable declares the type and name of the variable,
while the definition reserves storage for the variable as well as behaves as a
declaration.
The keyword extern is specified in declaration but not in definition.
For example the definition of an external variable salary will be written as-
float salary;
The features of the variable defined to have an external storage classes are
Storage: Primary memory
Default initial value 0
Scope global
Life time As long as the program execution does not come to an
end
In this program the variable x will be available to all the functions, since an external variable is
active from the point of its definition till the end of a program.
Till now we had written our program in a single file. When the program is large, it is written in
different files and these files are compiled seperately and linked together afterwards to form an
executable program. Now we’ll consider a multifile program, which is written in 3 files viz.
first.c, second.c and third.c
First.c Second.c Third.c
Here in the first.c , an external variable x is defined and initialized. This variable can be
used both in main() and func1() and it can be accessible to other files.
In the file second.c, to access this variable then we used the declaration in this file as
extern int x;
Suppose our program consists of many files and in file first.c, we have defined many variables
that may be needed by other files also.
We can put an extern declaration for each variable in every file that needs it.
Another better and practical approach is to collect all extern declarations in a header file and
include that header file in the files, which require access to those variables.
4. static variables:
As the name suggests, the value of static variables will be retained until the end of the
program. The features of a variable defined to have a static storage class are
Storage memory
Default initial value 0
Scope Local to the block in which the variable defined
Life time Until program ends
If a static variable is not explicitly initialized then by default it takes initial value zero.
Example:
Output:
Note:
The effect of initialization is seen only in the first call. In subsequent calls initialization is not
performed and variables x and y contain values left by the previous function call.
The next program uses a recursive function to find out the sum of digits of a number. The
variable sum taken inside function sumd() should be taken as static.
Output:
b) global static variable:
It is declared outside of all functions and is available to all the functions in that
program.
If a local variable is declared as static then it remains same throughout the program.
In case of global varaibles, the static specifier is not used to extend the lifetime since
global variables have already a lifetime equal to the life of program.
Here the static specifier is used for information hiding.
If an external variable is defined as static, then it cant be used by other files of the
program. We can make an external variable private to a file by making it static.
First.c Second.c Third.c
Here the variable y is defined as a static external variable, so it can be used only in the file
first.c We cant use it in other files by putting extern declaration for it.
Local variables have no linkage, so their scope is only within the block where they are
declared.
Global variables and functions have external linkage, so they can be used in any file of
the program.
static global variables and static functions have internal linkage, so their scope is only
in the file where they are declared.
RECURSION
Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been satisfied.
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.
When writing recursive functions, we must have a conditional statement somewhere
in the function to force the function to return without the recursive call being executed
otherwise the function will never return and program goes into infinite loop.
Example:
Output:
Types of Recursion:
Any recursive function can be characterized based on the following:
1. Direct recursion:
A function is said to be directly recursive if it explicitly calls itself.
For example:
Here, the function func() calls itself for all positive values of n, so it is said to be a directly
recursive function.
2. Indirect recursion:
A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it. Look at the functions given below. These two functions are indirectly
recursive as they both call each other.
3. Tail Recursion:
A recursive function is said to be tail recursive, if no operations are pending to be performed
when the recursive function returns to its caller. When the called function returns, the
returned value is immediately returned from the calling function. Tail recursive functions are
highly desirable because they are much more efficient to use as the amount of information
that has to be stored on the system stack is independent of the number of recursive calls.
RECURSION ITERATIONS
1. Recursive function is a function that is 1. Iterative instructions are loop based
partially defined by itself. repetitions of a process.
2. Recursion uses selection structure 2. Iteration uses repetition structure
3. Infinite recursion occurs if the recursion 3. An infinite loop occurs with iteration if the
step does not reduce the problem in a manner loop condition test never becomes false.
that converges on some condition.(base case)
4. Recursion terminates when a base case is 4. Iteration terminates when the loop-
recognized condition fails
5. Recursion is usually slower than iteration 5. Iteration does not use stack so it’s faster
due to overhead of maintaining stack. than recursion
6. Recursion uses more memory than 6. Iteration consume less memory
iteration.
7. Infinite recursion can crash the system. 7. Infinite looping uses CPU cycles
repeatedly.
8. Recursion makes code smaller. 8. Iteration makes code longer
INTER-FUNCTION COMMUNICATION
A function is a self-contained block or sub program that perform a special task when it
is called.
Whenever a function is called to perform a specific task, then the called function
performs that task and the result is returns back to the calling function.
The data flow between the calling and called functions to perform a specific task is
known as inter function communication.
Different methods for transferring data between calling and called function.
The data flow between the calling and called functions can be divided into three strategies:
(i) Downward flow
(ii) Upward flow
(iii) Bi-directional flow.
Output:
4
In this example, only one element of the array is passed to the called function. This is done by
using the index expression.. So arr[3] actually evaluates to a single integer value.
However, in the called function, the value of the array element must be accessed using the
indirection(*) operator.
Program:
Output:
2
The program illustrates the code which passes the entire array to the called function.
Output:
1
2
3
4
5
Output:
7
(2) PASSING A ROW:
A row of 2D array can be accessed by indexing the array name with the row number. When we
send a single row of a two-dimensional array, then the called function receives a one-
dimensional array.
Program:
Output:
4
5
6
(3) PASSING THE ENTIRE ARRAY:
To pass a 2D array to a function, we use the array name as the actual parameter. (The same we
did in case of a 1D array). However, the parameter in the called function must indicate that the
array has 2 dimensions.
Program:
Output:
Enter the number of rows and columns of the matrix= 2 2
Enter array elements
1 2 3 4
1 2
3 4
Standard Functions in C
The standard functions are built-in functions.
In C programming language, the standard functions are declared in header files and
defined in .dll files.
In simple words, the standard functions can be defined as "the ready made functions
defined by the system to make coding more easy".
The standard functions are also called as library functions or pre-defined functions.
In C when we use standard functions, we must include the respective header file using
#include statement.
For example, the function printf() is defined in header file stdio.h (Standard Input
Output header file).
When we use printf() in our program, we must include stdio.h header file using
#include<stdio.h> statement.
C Programming Language provides the following header files with standard functions.
Header
Purpose Example Functions
File
stdio.h Provides functions to perform standard I/O operations printf(), scanf()
conio.h Provides functions to perform console I/O operations clrscr(), getch()
math.h Provides functions to perform mathematical operations sqrt(), pow()
string.h Provides functions to handle string data values strlen(), strcpy()
stdlib.h Provides functions to perform general functions/td> calloc(), malloc()
time.h Provides functions to perform operations on time and date time(), localtime()
Provides functions to perform - testing and mapping of
ctype.h isalpha(), islower()
character data values
setjmp.h Provides functions that are used in function calls setjump(), longjump()
Provides functions to handle signals during program
signal.h signal(), raise()
execution
Provides Macro that is used to verify assumptions made
assert.h assert()
by the program
Defines the location specific settings such as date formats
locale.h setlocale()
and currency symbols
Used to get the arguments in a function if the arguments va_start(), va_end(),
stdarg.h
are not specified by the function va_arg()
errno.h Provides macros to handle the system calls Error, errno
graphics.h Provides functions to draw graphics. circle(), rectangle()
float.h Provides constants related to floating point data values
stddef.h Defines various variable types
Defines the maximum and minimum values of various
limits.h
variable types like char, int and long
Preprocessor Commands in C
In C programming language, preprocessor directive is a step performed before the
actual source code compilation.
It is not part of the compilation.
Preprocessor directives in C programming language are used to define and replace
tokens in the text and also used to insert the contents of other files into the source file.
When we try to compile a program, preprocessor commands are executed first and then
the program gets compiled.
Every preprocessor command begins with # symbol. We can also create preprocessor
commands with parameters.
#define
#define is used to create symbolic constants (known as macros) in C programming language.
This preprocessor command can also be used with parameterized macros.
#undef
#undef is used to destroy a macro that was already created using #define.
#ifdef
#ifdef returns TRUE if the macro is defined and returns FALSE if the macro is not defined.
#ifndef
#ifndef returns TRUE if the specified macro is not defined otherwise returns FALSE.
#if
#if uses the value of specified macro for conditional compilation.
#else
#else is an alternative for #if.
#elif
#elif is a #else followed by #if in one statement.
#endif
#endif is used terminate preprocessor conditional macro.
#include
#include is used to insert specific header file into C program.
#error
#error is used to print error message on stderr.
#pragma
#pragma is used to issue a special command to the compiler.
In C programming language, there are some pre-defined macros and they are as follows...
1. __ DATE __ : The current date as characters in "MMM DD YYYY" format.
2. __ TIME __ : The current time as characters in "HH : MM : SS" format.
3. __ FILE __ : This contains the current file name.
4. __ LINE __ : This contains the current line number.
5. __ STDC __ : Defines 1 when compiler compiles with ANSI Standards.
PROGRAMMING EXAMPLES
1. Write a program to find biggest of three integers using functions?
Program:
Output:
Write a C program to print Fibonacci series using recursion?
Program:
Output: