Unit 5
Unit 5
Functions: Need of Functions, Function Declaration, Definition and Call. Inbuilt functions and User Defined
Functions. Passing arguments to a function, Returning values from a function. Scope of variable, local and global
variable. Storage classes.
Recursive Functions: Need of Recursion, Direct Recursion, Indirect Recursion, Examples of Recursive Programs
– Factorial, Fibonacci series. Recursive Vs Iterative solutions,Disadvantages of Recursion.
Functions in C:
The function is a self contained block of statements which performs a coherent task of a
same kind.
C program does not execute the functions directly. It is required to invoke or call that
functions. When a function is called in a program then program control goes to the
function body. Then, it executes the statements which are involved in a function body.
Therefore, it is possible to call function whenever we want to process that functions
statements.
Advantages of functions:
1. Many programs require that a specific function is repeated many times instead of
writing the function code as many timers as it is required we can write it as a single
function and access the same function again and again as many times as it is required.
2. We can avoid writing redundant program code of some instructions again and again.
3. Programs with using functions are compact & easy to understand.
4. Testing and correcting errors is easy because errors are localized and corrected.
5. We can understand the flow of program, and its code easily since the readability is
enhanced while using the functions.
6. A single function written in a program can also be used in other programs also.
Concept of Function
########################
Purpose of function
############################
USING FUNCTIONS
##########################
Function Definition
#######################
Function Calling
############################
Return Statement
################################
Characteristics of Function
####################
Advantages of Functions
##########################
Types of functions:
There are 2(two) types of functions as:
1. Built in Functions
2. User Defined Functions
1. Built in Functions :
These functions are also called as 'library functions'. These functions are provided by
system. These functions are stored in library files.
Examples:
main()
- The execution of every C program starts from this main.
printf()
- prinf() is used for displaying output in C.
scanf()
- scanf() is used for taking input in C.
2. User defined function
C provides programmer to define their own function according to their requirement
known as user defined functions.
Example of how C function works
#include <stdio.h>
void function_name(){
................
................
}
int main(){
...........
...........
function_name();
...........
...........
}
As mentioned earlier, every C program begins from main() and program starts executing
the codes inside main function. When the control of program reaches to function_name()
inside main. The control of program jumps to "void function_name()" and executes the
codes inside it. When, all the codes inside that user defined function is executed, control
of the program jumps to statement just below it. Analyze the figure below for
understanding the concept of function in C.
#include <stdio.h>
if (n1>n2)
big = n1;
else
big = n2;
return (big);
}
void main ()
{
double x, y, result;
printf ("Enter a real number: ");
scanf ("%lf", &x);
}
Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype gives compiler
information about function name, type of arguments to be passed and return type.
Syntax of function prototype
return_type function_name(type(1) argument(1),....,type(n) argument(n));
Here, in the above example, function prototype is "int add(int a, int b);" which provides
following information to the compiler:
1. name of the function is "add"
2. return type of the function is int.
3. two arguments of type int are passed to function.
Function prototype is not needed, if you write function definition above the main function.
Function call
Control of the program cannot be transferred to user-defined function (function definition)
unless it is called (invoked).
Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument a should be
of int type and b should be of float type in function definition. i.e. type of argument during
function call and function definition should be same.
A function can be called with or without an argument.
Function parameters / Arguments
There are Two types of function parameters. They are
(i)Actual Parameters
The parameters that are mentioned in the function call are said to be actual parameters.
(ii) Formal Parameters
The parameters that are mentioned in the function declaration are said to be formal
parameters.
In the above example, num1 and num2 are Actual Parameters.
Where as a and b are Formal Parameters.
NESTING OF FUNCTIONS
############
STANDARD/LIBRARY FUNCTIONS
##################################
SCOPE OF VARIABLES
###########
RECURSION VS ITERATION
################
Return Statement
Return statement is used for returning a value from function definition to calling
function.
Syntax of return statement
return (expression);
OR
return;
For example:
return; // returns a garbage value back to the calling function
return a; // returns value of ‘a’ back to the calling function
return(a+b); /* returns the value that is produced after evaluating the expression a+b */
Note that, data type of add is int and also the return type of function is int. The data type
of expression in return statement should also match the return type of function.
User defined functions are classified into 4 types depending on Arguments and their
Return values
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.
**Note that the value return by any function when no format is specified is an
integer
Parameter passing mechanisms
Pass By Value
Passing a variable by value makes a copy of the variable before passing it onto a function.
This means that if you try to modify the value inside a function, it will only have the
modified value inside that function. One the function returns, the variable you passed it
will have the same value it had before you passed it into the function.
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
printf("Swapped values are a = %d and b = %d", x, y);
}
void main()
{
Output:
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7
The values after swap are a = 7 and b = 4
Pass By Reference
There are two instances where a variable is passed by reference:
1. When you modify the value of the passed variable locally and also the value of the
variable in the calling function as well.
2. To avoid making a copy of the variable for efficiency reasons.
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("Swapped values are a = %d and b = %d", *x, *y);
}
void main()
{
int a = 7, b = 4;
printf("Original values are a = %d and b = %d",a,b);
swap(&a, &b);
printf("The values after swap are a = %d and b = %d",a,b);
}
Output:
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7
The values after swap are a = 4 and b = 7
Storage Classes:
'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a variable can be used. Storage
class defines the the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a
computer where variable is stored. There are two memory locations in a computer system
where variables are stored as : Memory and CPU Registers.
Functions of storage class :
To determine the location of a variable where it is stored?
Example :
auto int a;
Program
#include <stdio.h>
#include <conio.h>
void main()
{
auto int i=10;
clrscr();
{
auto int i=20;
printf("\n\t %d",i);
}
Explanation
During first function call, it will display 0. Then, during second function call, variable c
will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second
function call and 10 in third call.
If variable c had been automatic variable, the output would have been:
0 0 0
Void Check ()
{
++a; /* Variable a is not declared in this function but, works in any function as they
are global variable */
printf ("a=%d\n",a);
}
Output
a=10
SCOPE RULES:
1. The scope of a global variable is the entire program file.
2. The scope of a local variable begins at point of declaration and ends at the end of the
block or function in which it is declared.
3. The scope of a formal function argument is its own function.
4. The life time of an auto variable declared in main( ) is the entire program exception
time
,although its scope is only the main function .
5. The life of an auto variable declared in a function ends when the function is exited.
6. A static local variable ,although its scope is limited to its function,its life time extends
till the end of program execution.
7. All variables have visibility in their scope, provided they are not declared again.
8. If a variable is redeclared within its scope again,it loses its visibility in the scope of the
redeclared variable.
Department of BS&H Page 108
NRI Institute of Technology, Pothavarappadu
Type Qualifiers:
Constants:
The Keyword for the constant type qualifier is const.
A constant object is a read-only object,that is , it can only be used as rvalue.A constant
object must be initialized when it is declared because , it cannot be changed later.A
simple constant is shown below.
Example: const double pi=3.1414926;
Const char str[]=”hello”;
Volatile:
The Keyword for the volatile type qualifier is volatile
The volatile qualifier tells the computer that an object value may be changed by
entities other than this program.
Example: volatile int x;
volatile int *ptr;
Block Structure :
C is not a block-structured language in the sense of Pascal or similar languages, because
functions may not be defined within other functions. On the other hand, variables can be
defined in a block-structured fashion within a function. Declarations of variables
(including initializations) may follow the left brace that introduces any compound
statement, not just the one that begins a function. Variables declared in this way hide
any identically named variables in outer blocks, and remain in existence until the
matching right brace. For example, in
if (n > 0) {
int i; /* declare a new i */
for (i = 0; i < n; i++)
...
}
RECURSION
A Function calling itself is called recursion. Any function can call any function including
itself. In this scenario, if it happens to invoke a function by itself, it is recursion. One of
the instructions in the function is a call to the function itself, usually the last statement.
In some ways it is similar to looping. When the result of ‘one time call of a function is the
input for the next time call of the function’, recursion is one of the best ways. For
example, calculating factorial, in which the product of previous digit factorial is the input
for the next digit’s factorial.
Basic elements of Recursion
A test to stop or continue the recursion
An end case that terminates the recursion
A recursive call(s) that continues the recursion
Types of recursion
1) Direct recursion occurs when a method invokes itself, such as when sum calls sum.
Ex: int sum()
{
---------
2) Indirect recursion occurs when a method invokes another method, eventually resulting
in the original method being invoked again.
Int calc()
{
-------
Sum();
}
Examples of Recursion
1) Ex : Calculation of factorial
Factorial of n (denoted n!) is a product of integer numbers from 1 to n. For instance, 5! = 1
* 2 * 3 * 4 * 5 = 120.
Recursion is one of techniques to calculate factorial. Indeed, 5! = 4! * 5. To calculate
factorial of n, we should calculate it for (n-1). To calculate factorial of (n-1) algorithm
should find (n-2)! and so on.
int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
The above program works as follows,
fact(3) = {if(3= =1) is false thus return 3* fact (2)}
fact(2) = {if(2= =1) is false thus return 2* fact (1)}
fact(1) = {if(1= =1) is true thus return 1}
Calculation of 3! in details
output:-
Enter the number 6 /* here given 6 as input */
PROGRAM
#include<stdio.h>
int Fibonacci(int);
main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
void main()
{
int arr[3] = {1,2,3};
int i;
void show(int x)
{
printf("%d\t ",x);
}
Output
1 2 3
Write a C program to display all prime numbers within the range specified by user
using functions.
#include<stdio.h>
int check_prime(int num);
int main(){
int n1,n2,i,flag;
printf("Enter the range:\
n"); scanf("%d
%d",&n1,&n2);
for(i=n1+1;i<n2;++i){
flag=check_prime(i);
if(flag==1)
printf("%d ",i);
}
return 0;
}
int check_prime(int num)
{ int j,temp=1;
for(j=2;j<=num/2;++j){
if(num%j==0){
temp=0;
break;
}
}
return temp;
}
Functions: Need of Functions, Function Declaration, Definition and Call. Inbuilt functions and
Passing arguments to a function, Returning values from a function. Scope of variable, local and
global variable.
#############################################
Recursive Functions: Need of Recursion, Recursive Vs Iterative solutions, Disadvantages of
Recursion.
##################################
Additional programs
####################################