PPS Chapter-5
PPS Chapter-5
Subject
Programming for Problem Solving (3110003)
Chapter – 5
Functions
CONTENTS
1. CONCEPTS OF FUNCTIONS
2. DEFINITION OF FUNCTION
3. PROTOTYPES OF FUNCTION (OR FUNCTION DECLARATION)
4. CALLING A FUNCTION
5. PARAMETER PASSING TO FUNCTION
5.1. Call by Value
5.2. Call by Reference
6. CATEGORIES/TYPES OF FUNCTIONS
6.1. Functions with No Arguments and No Return Values
6.2. Functions with No Arguments and Return Values
6.3. Functions with Arguments and No Return Values
6.4. Functions with Arguments and Return Values
7. SCOPE OF VARIABLES
8. RECURSIVE FUNCTIONS
9. PRE-PROCESSING (C PRE-PROCESSOR)
10. MACROS
1. CONCEPTS OF FUNCTIONS
• Function is a block of code which is defined to perform specific task repeatedly.
Set of functions are combined to form a program.
• Every C program has at least one function called as main() function. The
execution of every programs starts from main() function.
Advantages of Functions:
o By using functions, we can avoid rewriting same logic/code again and again
in a program.
o We can call C functions any number of times in a program and from any
place in a program.
o We can track a large C program easily when it is divided into multiple
functions.
o Reusability is the main achievement of C functions.
Types of Functions:
o There are two types of functions in C programming:
1. Library Functions: the functions which are readily available in C
library are called as library functions or built-in functions such as
scanf(), printf(), gets(), puts(), etc.
2. User-defined Functions: the functions which are created by
programmer in a program are called as user-defined functions.
2. DEFINITION OF FUNCTION
• A block of code which is intended to perform a specific task is called as function.
Return type:
• A function may or may not return a value. The return type is the type of the
value which the function returns.
• By default, a function returns integer value so the return type is int by default.
• If a function doesn’t return any value, then the return type will be void.
Function name:
• It is the name of the function and is any valid C identifier.
• Function name is starts with a letter or underscore and then followed by any
combination of letters, digits, or underscores.
• Function name doesn’t allow space.
Function body:
• The function body include a set of statements that define operation of the
function.
• The function body is enclosed in { and } braces.
• It consists of three parts:
o Declaration of local variables needed by function.
o Executable statements that perform task of function.
o Returned value as the output of function.
• Local variables are variables that are defined within function and their life is
only till that function and cannot be used outside the function.
• The return statement returns the expression or the value needed. Absent of
return statement in function body indicates that no value is being returned to
the calling function.
• Here div is the function name. It performs division. div returns an integer
value.
• The result is local variable.
• The variables a and b are two parameters of div.
• a and b are called formal parameters.
• C function can take any number of formal parameters but it can return at
most one value per call.
• Function declaration which is also referred as function prototype has four parts
as below:
1. Return type
2. Function name
3. List of formal parameters
4. Semicolon
• These elements are same as the function header in function definition except the
semicolon.
• It is possible to have different parameter names in function prototype from the
names having in function definition.
• But it is mandatory to match return type in function prototype with return type in
function definition.
• Also, type, order, and the number of formal parameters of list in function
prototype should match with type, order, and number of formal parameters in
function definition.
Prepared by – Prof. Viral H. Panchal 5
Programming for Problem Solving (3110003) Chapter – 5: Functions
• Function declaration is done in global section i.e., after header files and above
all the functions including main().
• Globally declared functions are available to all the functions in the program.
• Also we can declare a function inside a function; this is called local declaration so
its life is limited to the function in which it is declared.
#include<stdio.h>
#include<conio.h>
int div(int a, int b); Function prototype
void main()
{
...
...
}
• If return type is absent then it is assumed that the function returns int value or
no value.
• Parameter names are optional in function prototyping.
• We can declare div function in following ways:
void add(void);
4. CALLING A FUNCTION
• To use defined function, me must call it.
• Following syntax is used to call a function.
• Before calling any function, it should be either declared or defined first and then
function call be made, otherwise compiler will generate error.
Example:
#include<stdio.h>
#include<conio.h>
void greater(int, int); //function prototype
void main()
{
int x=6,y=5;
greater(x,y); //function call
getch();
}
void greater(int a, int b) //function definition
{
if(a>b)
{
printf("%d is greater number",a);
}
else
{
printf("%d is greater number",b);
}
}
Output:
6 is greater number
Explanation:
• In this program main() is the calling function and greater() is called function.
• While the function greater() gets called by main(), further execution of
main() is suspended and the control goes to the definition of greater()
function and the values of x and y are mapped to a and b respectively.
• After finding the greater number the control goes back to the calling function
i.e., main() again and continues its further execution.
#include<stdio.h>
#include<conio.h>
void swap(int x, int y); //x and y formal parameters
void main()
{
int a,b; //local variables
printf("Enter the value of a: ");
scanf("%d",&a);
printf("Enter the value of b: ");
scanf("%d",&b);
swap(a,b); //call by value, a and b actual parameters
getch();
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("\nAfter Swapping: \na = %d \nb = %d",x,y);
}
Output:
Enter the value of a: 23
Enter the value of b: 35
After Swapping:
a = 35
b = 23
• In the above program, values entered for the variables a and b in the main()
function are passed to the function swap().
• These values get copied into the memory location of the arguments x and y,
respectively, of the function swap() when it is called.
• This is shown below:
Contents of
a b actual arguments
23 35
23 35
x y formal arguments
• The most important point to remember while using arguments is that the actual
and formal arguments should match in number, type, and order.
• The actual and formal parameters use different memory locations and any
change in formal arguments is not reflected back in the calling function using call
by value method.
• In the call by reference method, the addresses of the actual arguments in the
calling function are copied into the formal arguments of the called function.
• So, the called function refers to the original values by the address it accepts.
• The following program illustrates the concepts of call by reference method.
#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y); //x and y formal parameters
void main()
{
int a,b; //local variables
printf("Enter the value of a: ");
scanf("%d",&a);
printf("Enter the value of b: ");
scanf("%d",&b);
swap(&a,&b); /*call by reference, addresse of a and b
passes to swap()*/
getch();
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf("\nAfter Swapping: \na = %d \nb = %d",*x,*y);
}
Output:
Enter the value of a: 23
Enter the value of b: 35
After Swapping:
a = 35
b = 23
• Here, the main() function calls the function swap() by passing the addresses of a
and b by the statement
swap(&a,&b);
Contents of
a b actual arguments
23 35
Address passed
37105 37120
x y formal arguments
x points to a y points to b
• To summarize: The way a call by value works is probably similar to the case
where a college principal asks a head of department to send student named
Dhruvin to him, i.e., asking for the student by name, as opposed to what
probably by a call by reference if the principal asked for the student of class BE
1st Year whose roll number is 10 (Assuming that 10 is Dhruvin’s roll number).
6. CATEGORIES/TYPES OF FUNCTIONS
• Based on the arguments and return types, the user defined functions can be
categorized into one of the following four types:
• To call the function with no return values and no arguments, the following format
is used.
function_name();
• An empty parenthesis indicates that the function call does not pass any
parameter.
• Example:
#include<stdio.h>
#include<conio.h>
void add(void); //function declaration
void main()
{
add(); //function call
getch();
}
void add() //function definition
{
int a=5,b=45;
int c;
c=a+b;
printf("\nAddition Result: %d + %d = %d",a,b,c);
}
Output:
Addition Result: 5 + 45 = 50
• To call the function with return type but no arguments, the following format is
used.
variable_name = function_name();
#include<stdio.h>
#include<conio.h>
int add(); //function declaration
void main()
{
int c;
c = add(); //function call
printf("\nAddition Result: %d",c);
getch();
}
int add() //function definition
{
int a=5,b=45;
int c;
c=a+b;
return(c);
}
Output:
Addition Result: 50
• To call the function with arguments and no return, the following format is used.
function_name(list of actual parameters);
#include<stdio.h>
#include<conio.h>
void add(int a, int b); //function declaration
void main()
{
int a=10, b=20;
add(a,b); //function call
getch();
}
void add(int a, int b) //function definition
{
int c;
c=a+b;
printf("\nAddition Result: %d + %d = %d",a,b,c);
}
Output:
Addition Result: 10 + 20 = 30
• To call the function with arguments and return value, the following format is used.
variable_name = function_name(list of actual parameters);
#include<stdio.h>
#include<conio.h>
int add(int a, int b); //function declaration
void main()
{
int a,b,c;
a=90, b=80;
c=add(a,b); //function call
printf("\nAddition Result: %d + %d = %d",a,b,c);
getch();
}
int add(int a, int b) //function definition
{
int c;
c=a+b;
return(c);
}
Output:
Addition Result: 90 + 80 = 170
7. SCOPE OF VARIABLES
• By scope of a variable, we mean in what part of the program the variable is
accessible.
• In what part of the program the variable is accessible is dependent on where the
variable is declared.
• There are two types of scope: Local and Global.
Local Variables:
• Scope of the local variable is limited to the function in which it is declared.
Other functions can not have access to that variable.
• Default value of local variable is garbage.
• Local variables are declared within function.
Global Variables:
• Scope of the global variable is throughout the program i.e., every function in
the program can access such variable.
• Global variables are declared outside all the functions (including main()).
• Default value of global variable is zero.
• Example:
#include<stdio.h>
#include<conio.h>
void display (int a);
int a=50; //Global variable
void main()
{
int i=20; //Local variable of main()
printf("In main() function \na = %d\ni = %d",a,i);
display(i);
getch();
}
void display (int j)
{
int k=35; //Local variable of display()
printf("\nIn display() function \na = %d\nj = %d\nk = %d",
a,j,k);
}
Output:
In main() function
a = 50
i = 20
In display() function
a = 50
j = 20
k = 35
Explanation:
8. RECURSIVE FUNCTIONS
• The process of calling a function inside itself is called as recursion.
• The function which calls itself is referred to as recursive function.
Advantages:
• Easy solution for recursively defined problems.
• Complex programs can be easily written in less code.
Disadvantages:
• Recursive code is difficult to understand and debug.
• Terminating condition is must, otherwise it will go in infinite loop.
• Execution speed decreases because of function call and return activity many
times.
#include<stdio.h>
#include<conio.h>
void main()
{
printf("\nThis is an example of recursion");
main();
}
• When executed, this program will produce an output something like this:
This is an example of recursion
This is an example of recursion
This is an example of recursion
This is an ex
#include<stdio.h>
#include<conio.h>
int fact (int n);
void main()
{
int n,f;
printf("Enter a number for finding factorial: ");
scanf("%d",&n);
f=fact(n);
printf("\nFactorial of %d = %d",n,f);
getch();
}
int fact (int n)
{
int f;
if(n==1)
{
return(1);
}
else
{
f=n*fact(n-1);
}
return(f);
}
Output:
Enter a number for finding factorial: 6
Factorial of 6 = 720
#include<stdio.h>
#include<conio.h>
int fib (int n);
void main()
{
int n,i,ans;
printf("How many Fibonacci Numbers?\n");
scanf("%d",&n);
printf("The Fibonacci Numbers are:\n");
for(i=0;i<n;i++)
{
ans=fib(i);
printf("%5d",ans);
}
getch();
}
int fib (int n)
{
if(n==0)
return(0);
else if(n==1)
return(1);
else
return(fib(n-1)+fib(n-2));
}
Output:
How many Fibonacci Numbers?
7
The Fibonacci Numbers are:
0 1 1 2 3 5 8
9. PRE-PROCESSING (C PRE-PROCESSOR)
• The C pre-processor is a microprocessor that is used by compiler to transform
your code before compilation. It is called micro pre-processor because it allows
us to add macros.
• All pre-processor directives start with hash # symbol.
• List of pre-processor directives are as follows.
o #include
o #define
o #undef
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma
• Some of the common uses of C pre-processor are:
o Include header files
o Macros
o Conditional compilation
o Diagnostics
o Line control
o Pragmas
o Other directives
o Pre-processor output
10. MACROS
• A macro is a segment of code which is replaced by the value of macro. Macro is
defined by #define directive.
• There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros:
• The object-like macro is an identifier that is replaced by value. It is widely
used to represent numeric constants.
• For example:
#define PI 3.14
• Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros:
• The function-like macro looks like function call.
• For example:
Output:
3.140000
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main()
{
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
Output:
Minimum between 10 and 20 is: 10
C Predefined Macros:
• ANSI C defines many predefined macros that can be used in c program.
Macro Description
_DATE_ represents current date in "MMM DD YYYY" format.
_TIME_ represents current time in "HH:MM:SS" format.
_FILE_ represents current file name.
_LINE_ represents current line number.
_STDC_ It is defined as 1 when compiler complies with the ANSI standard.
#include<stdio.h>
int main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
return 0;
}
Output:
File :main.c
Date :Jun 7 2022
Time :15:15:57
Line :7
STDC :1