Unit-4... PPS
Unit-4... PPS
FUNCTIONS
4.1 Designing Structured Programs:
A function is a self contained program segment that carries out a specific, well-defined task.
1. Library Functions
2. User defined Functions
The library functions are pre-defined set of functions. Their task is limited. A user
cannot understand the internal working of these functions. The user can only use the
functions but can‟t change or modify them.
Ex: sqrt(81) gives result 9. Here the user need not worry about its source code, but the result
should be provided by the function.
The User defined functions are totally different. The functions defined by the user
according to his requirement are called as User defined functions. The user can
modify the function according to the requirement. The user certainly understands the
internal working of the function. The user has full scope to implement his own ideas
in the function. Thus the set of such user defined functions can be useful to another
programmer. One should include the file in which the user-defined functions are
stored to call the functions in the program.
Ex: Let square(9) is user-defined function which gives the result 81.
Here the user knows the internal working of the square() function, as its source code is
visible. This is the major difference between the two types of functions.
Why we use functions?
3. Like variables, function names and their types must be declared and defined before they are
used in a program.
In order to make use of a user-defined function, we need to establish three elements that are
related to functions.
1. Function declaration
2. Function call
3. Function defining
4.3Signature of function
For Example
Declaration of a function with no input parameters
void printMatrix();
Declaration of a function with one input parameter and integer return type
int isEvenNumber(int num);
Declaration of a function with multiple input parameter and integer return type.
int getSum(int num1, int num2);
Declaration of a function with no input parameters and integer return type.
int getRandomNumber();
Important Points about Function Declaration:
Function type
function name,
list of parameters (arguments)
local variable declarations
body of the functions (list of statements)
a return statement.
All the six elements are grouped into two parts, namely,
The type_specifier specifies the data type of the value, which the function will return.
If no data type is specified, the function is assumed to return an integer result. The
arguments are separated by commas. A function is not returning anything; then we
need to specify the return type as void. A pair of empty parentheses must follow the
function name if the function definition does not include any arguments.
The parameters list / arguments list declares the variables that will receive the data
sent by the calling program. They serve as input data to the function o carry out the
specific task.
4.4.1 Parameters:
The body of the function may consist of one or many statements necessary for performing
the required task. The body consists of three parts:
1. Local variable declaration
2. Function statements that perform the task of the function
3. A return statement that returns the value evaluated by the function. If a function is not
returning any value then we can omit the return statement.
EX: 1. /* program to call main function from another user defined function*/
void main()
{
message();
}
void message ( )
{
printf(“\n welcome to C lab”);
main();
The value evaluated by any function is send back to the calling function by using return
statement. The called function can only return only one value per call. The return statement has
the following forms:
return;
return(expression);
The first form does not return any value to the calling function; it acts as the closing
brace of the function. When a return is encountered, the control is immediately passed
back to the calling function.
A function may have more than one return statement. This situation arises when the value
returned is based on certain conditions:
EX:
if(a>b)
return(1);
else
return(0);
Note:
All functions by default return integer type data. But, we can force a function to return a
particular type of data by using a type specifier in the function header as discussed
earlier.
Absence of return statement in called function indicates that no value is returned to the
calling function, such functions are called as void.
Once a function is defined and called, it takes some data from the calling function and
returns a value to the called function.
Whenever a function is called, control passes to the called function and working of the
calling function is stopped. When the execution of the called function is completed,
control returns back to the calling function and execute the next statement.
The values of actual arguments passed by the calling function are received by the formal
arguments of the called function. The number of actual and formal arguments should be
the same.
Extra arguments are discarded if they are defined. If the formal arguments are more than
the actual arguments then the extra arguments appear as garbage. Any mismatch in data
type will produce the unexpected result.
The function operates on formal arguments and sends back the result to the calling
function. The return ( ) statement performs this task.
4.5 Passing parameters to function:
Depending upon the arguments present, return value send the result back to the calling function.
Based on this, the functions are divided into 4 types:
In this type neither the data is passed through the calling function nor is the data sent back from
the called function.
If the functions are used to perform any operations, they act independently. They read data
values and print result in the same block.
This type of functions may be useful to print some messages, draw a line or split the line etc.
{
void message ( ); /*FUNCTION PROTOTYPE*/
message ( ); /*FUNCTION CALL*/
}
void message ( ) /*FUNCTION DEFINITION*/
{
printf(“Have a nice day”); }
z=add(); No arguments are passed. y=a+b;
printf(“sum = %d”,z); No values are sent back return(y);
} }
In this type of function no arguments are passed through the main ( ) function (calling function).
But the called function (add ( )) returns the values. Here the called function is independent. It re
data from the keyboard or generates form the initialization and returns the values. In this type
both the calling function and called function are partly communicated with each other.
In this type of functions arguments are passed to the calling function. The called function
operates on the values. But no result is sent back. This called function is also partly dependent on
the calling function. The result obtained is utilized in the called function only.
void main ( )
{
void add (int, int); /* FUNCTION PROTOTYPE */
int a, b; add (int x,int y) /* FUN DEFINITION*/
clrscr( ); {
printf(“enter the values of a and b”); int z; /*Local variable declaration*/
scanf(“%d%d”, &a,&b); z = x+y;
add(a,b); /* FUNCTION CALL */ printf(“sum = %d”,z);
getch( ); }
}
Explanation: in this program two values are passed to add ( ) function. The add ( ) function
receives argument from main ( ) and displays sum of a and b. But it returns nothing.
In this type of functions a copy of actual argument is passed to the formal argument from the
calling function to the called function. Called function operates on those data values and it will
return the result to the calling function. Here data is transferred between calling and called
functions.
The technique of passing data from one function to another is known as parameters passing.
Parameter passing can be done in two ways:
Call by value
Call by reference
In this type value of actual arguments are passed to the formal arguments and the operation is
done on the formal arguments. Any change made in the formal arguments does not affect the
actual arguments because formal arguments are photocopy of actual arguments.
Changes made in the formal arguments are local to the block of the called function. Once the
control returns back to the calling function the changes made vanish.
void main( )
{
int a,b;
printf(“enter any two values\n”);
scanf(“%d%d”,&a,&b);
swap(a,b);
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
printf(“after interchange\n”);
printf(“%d %d”,x,y);
}
In this type instead of passing values, addresses (reference) are passed. Function operates on
addresses rather than values. Here the formal arguments are pointers to the actual arguments.
Formal arguments point to the actual arguments. Hence the changes made in the arguments are
permanent. i.e., the changes made in formal arguments will affect the actual arguments.
/* Ex 2: Swapping of 2 numbers */
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main( )
{
int a,b;
printf(“enter any two values\n”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
printf(“after interchange\n”);
printf(“%d %d”,a,b);
getch( );
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Function returning more values:
We know that a function can return only one value per call. But we can force the function to
return more than one value per call by using call by reference.
void main( )
{
int x,y, add, sub, change (int*,int*,int*,int*);
clrscr();
printf(“\n enter values of x&y”);
scanf(“%d %d”, &x, &y);
change(&x, &y, &add, &sub);
printf(“\n Addition=%d \n Subtraction=%d”, add, sub);
getch();
}
change(int *a, int *b, int *c, int *d)
{
*c=*a+*b;
*d=*a-*b;
}
Explanation: In this program return statement is not used. Still function returns more than one
value. Actually, no values are returned. Once the addresses of the variables are available, we can
directly access them and modify their contents.
Note:
The memory address of any variable is unique.
If we declare the same variable for actual and formal arguments, their memory addresses will be
different from each other.
In „c‟, a number of pre-defined functions are available to perform various tasks. To use these
functions, we have to include the corresponding header file in which the function is available.
When any of the functions getchar ( ), qets ( ), putchar ( ), puts ( ), scanf( ), printf ( ) is used the
header file stdio.h has to be included.
sqrt ( ):-This function performs square root of the given number. Syntax:- sqrt (n);
log ( ):-This function returns natural logarithm of the given number. Syntax:- log (n);
log10 ( ):-This functions returns logarithm value of the given number to the base 10.
ceil ( ):-This function returns the next higher integer value of the given number. Syntax:- ceil(n);
Eg:- ceil (17.7)=18 ceil (16.1)=17.
floor( ):-This function returns the integer value less than or equal to the given number.
abs( ):-This functions returns the absolute value of a given, integer. Syntax:- abs (integer value);
fabs( ):-This functions returns absolute value (modulus) of a given floating point number.
atoi ( ):-This function converts the given string to an integer value. Syntax:- atoi(string);
atof ( ):-This function converts the given string into floating point value. Syntax:- atof (string);
(i) isalpha( ):-This function checks whether the given character is an alphabet (or)
not. If it is an alphabet, it returns a non-zero value and otherwise a zero value.
Syntax:- is alpha(„a‟); True
Eg:- isalpha (“a‟) True (non-zero)
isalpha(“2‟) Flase (zero)
isalnum( ):- This function checks whether the given character is an alphabet or a number. If true
it returns a non-zero value otherwise a zero value.
Eg:- isalnum(“1‟) True (non-zero)
isalnum(“q‟) False (zero)
isdigit ( ):-This function checks whether the given character is a digit or not. If true it returns a
non-zero value otherwise a zero value.
Eg:- isdigit (“a‟) True (non zero)
isdigit(“*‟) False (zero)
islower ( ):-This function checks whether the given character is a Lower case alphabet or not. If
it is a small letter it returns a non-zero value otherwise a zero value.
Eg:- islower (“b‟) True (non-zero)
islower(“A‟) False (zero)
isupper ( ):-This function checks whether the given character is a upper case alphabet or not. If it
is a capital letter is returns a non-zero value otherwise a zero value.
Eg: isupper (“B‟) True (non-zero)
Isupper(”q‟) False (zero)
toupper ( ):-This function converts the given small letters to an upper case letter.
tolower ( ):- This function converts the given capital letters to a Lower case letter.
toascii( ):-This function returns the equivalent ASCII value for the given character.
This function clears the previous output from the screen and displays the output of the current
program from the first line of the screen. This function is defined in conio.h header file.
Syntax: clrscr();
exit( ):
This function terminates the program. It is defined in the process.h header file.
Syntax: exit( );
4.9 Recursion
Recursion is a special case of process, where a function calls itself. A function is called recursive
if a statement within the body of a function calls the same function.
factorial(x)
int x;
{
if (x = =1)
return(1);
else
return(x * factorial(x-1));
}
When writing recursive functions, you must have an If stmt somewhere in the recursive function
to force the function to return without recursive call being executed. If you do not do this and
you call the function, you will fall in an indefinite loop, and will never return from the called
function.
/*program to find factorial of a given number using a Recursive function*/ #include<stdio.h>
int factorial(x)
int x;
{
if (x<=1)
return(1);
else
return(x*factorial(x-1));
}
main()
{
int n,fn;
clrscr();
printf("enter n");
scanf("%d",&n);
fn=factorial(n); /* Function Call */
printf("the factorial %d is %d\n",n,fn);
getch(); }
In case the value of n is 4, main() would call factorial() with 4 as its actual argument, and
factorial() will send back the computed value. But before sending the computed value, factorial()
calls factorial() and waits for a value to be returned.
int fib(int x)
{
if(x==1)
return 0;
else if(x==2)
return 1;
else
return(fib(x-1)+fib(x-2));
}
4.9.1 Limitations of Recursion:
Advantages
1. Reduce unnecessary calling of function.
2. Through Recursion one can Solve problems in easy way while its iterative solution is
very big and complex.
Disdvantages
1. Recursive solution is always logical and it is very difficult to trace.(debug and
understand).
2. In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
3. Recursion takes a lot of stack space, usually not considerable when the program is small
and running on a PC.
4. Recursion uses more processor time.
Four memory management functions are used with dynamic memory. Three of
them,malloc,calloc,and realloc,are used for memory allocation. The fourth ,free is used to return
memory when it is no longer needed. All the memory management functions are found in
standard library file(stdlib.h).
The malloc function allocates a block of memory that contains the number of bytes
specified in its parameter. It returns a void pointer to the first byte of the allocated memory. The
allocated memory is not initialized.
Declaration:
void *malloc (size);
The type size_t is defined in several header files including Stdio.h. The type is usually an
unsigned integer and by the standard it is guaranteed to be large enough to hold the maximum
address of the computer. To provide portability the size specification in malloc’s actual
parameter is generally computed using the sizeof operator. For example if we want to allocate an
integer in the heap we will write like this:
Pint=malloc(sizeof(int));
Malloc returns the address of the first byte in the memory space allocated. If it is not
successful malloc returns null pointer. An attempt to allocate memory from heap when memory
is insufficient is known as overflow.
The malloc function has one or more potential error if we call malloc with a zero size, the
results are unpredictable. It may return a null pointer or it may return someother implementation
dependant value.
Ex:
If(!(Pint=malloc(sizeof(int)))) // no
memory available
exit(100);
//memory available
…
In this example we are allocating one integer object. If the memory is allocated successfully,ptr
contains a value. If does not there is no memory and we exit the program with error code 100.
3. REALLOCATION OF MEMORY(realloc):
The realloc function can be highly inefficient and therefore should be used
advisedly. When given a pointer to a previously allocated block of memory realloc
changes the size of the block by deleting or extending the memory at the end of the
block. If the memory can not be extended because of other allocations realloc allocates
completely new block,copies the existing memory allocation to the new location,and
deletes the old allocation.
18 55 33 121 64 1 90 31 5 77
10 Integers
ptr
18 55 33 121 64 1 90 31 5 77 ? ? ? ? ?
15 Integers
After
Releasing Memory(free):When memory locations allocated by malloc,calloc or realloc are no
longer needed, they should be freed using the predefined function free. It is an error to free
memory with a null pointer, a pointer to other than the first element of an allocated block, a
pointer that is a different type then the pointer that allocated the memory, it is also a potential
error to refer to memory after it has been released.
Ptr ptr
Before After
free(ptr);
BEFORE AFTER
… …
free(ptr);
In the above example the 200 elements were allocated with calloc. When we free the
pointer in this case, all 200 elements are return to heap. First, it is not the pointers that are being
released but rather what they point to. Second , To release an array of memory that was allocated
by calloc , we need only release the pointer once. It is an error to attempt to release each element
individually.
Releasing memory does not change the value in a pointer. Still contains the address in the
heap. It is a logic error to use the pointer after memory has been released.
Array are closely related to pointers in C programming but the important difference between
them is that, a pointer variable takes different addresses as value whereas, in case of array it is
fixed.
This can be demonstrated by an example:
#include <stdio.h>
int main()
{
char charArr[4];
int i;
return 0;
}
When you run the program, the output will be:
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
1. WACP to Check given number is Prime and Armstrong Number or not using function.
2. Implement a c program to print 1 to 100 numbers without using loops.
ASSIGNMENT QUESTIONS
SET 1:
1. Differentiate call by value and call by reference.
2. Implement a C program to print factorial of given number using with arguments
and with return type.
SET 2:
1. Discuss recursive function with an example.
2. Implement a C program to find power and square root of any number using standard
functions.
SET 3:
1. Implement a c program to transpose the given matrix.
2. Implement a C program to factorial using recursive functions.
SET 4:
1. Discuss about storage classes.
2. Implement a C program to allocate memory for 10 integers dynamically.
SET 5:
1. Discuss about inter function communications.
2. List out the difference between malloc() and calloc()?
SET 6:
1. Explain the difference between static allocation and dynamic allocation?
2. Implement Fibonacci series using recursion.
Important questions
(c) Explain in detail about pass by value and pass by reference. Explain with a sample program?
(b) Write a C program to find the factors of a given integer using a function.
(i) What is meant by function prototype? Give an example for function prototype.
9. (a) Distinguish between getchar and scanf functions for reading strings.
(i) Write a program to count the number of words, lines and characters in a text.
10. (a) What do you mean by functions? Give the structure of the functions and explain about
the arguments and their return values.
(i) Write a C program that uses a function to sort an array of integers.