0% found this document useful (0 votes)
101 views22 pages

PPS Chapter-5

This chapter discusses functions in C programming. It covers key concepts like defining functions, function prototypes, parameters, return types, scope of variables, and recursion. The document explains that a function is a block of code that performs a specific task and can be called multiple times. It defines the elements of a function like the function header, body, return type, parameters, etc. Function prototypes declare a function's name, return type, and parameters before definition. Parameters can be passed into functions by value or by reference. Functions can return values or not.

Uploaded by

Viral Panchal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views22 pages

PPS Chapter-5

This chapter discusses functions in C programming. It covers key concepts like defining functions, function prototypes, parameters, return types, scope of variables, and recursion. The document explains that a function is a block of code that performs a specific task and can be called multiple times. It defines the elements of a function like the function header, body, return type, parameters, etc. Function prototypes declare a function's name, return type, and parameters before definition. Parameters can be passed into functions by value or by reference. Functions can return values or not.

Uploaded by

Viral Panchal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Programming for Problem Solving (3110003) Chapter – 5: Functions

Subject
Programming for Problem Solving (3110003)

Chapter – 5
Functions

Prepared by – Prof. Viral H. Panchal 1


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

Prepared by – Prof. Viral H. Panchal 2


Programming for Problem Solving (3110003) Chapter – 5: Functions

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.

2.1. Elements of Functions


• The function elements are combined into two parts:
1. Function header: Function header is made-up of the return type, function
name, and list of formal parameters enclosed in parentheses.
2. Function body: Function body consists of local variable declaration
statements, function statements, and a return statement.

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.

Prepared by – Prof. Viral H. Panchal 3


Programming for Problem Solving (3110003) Chapter – 5: Functions

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.

List of formal parameters:


• The formal parameter list is optional, it may be present or absent depending
on the need of the function.
• The formal parameter list declares the variables which hold the values sent by
calling function.
• The formal parameters in the list are separated by comma and the list is
enclosed in parentheses.
• The list consists of types of the parameters and name of the parameters.

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.

Syntax of function definition:

return_type function_name(list of formal parameters) Function header


{
local variable declaration; (if any)
statement 1;
statement 2;
Function body
...
...
return statement;
}

Prepared by – Prof. Viral H. Panchal 4


Programming for Problem Solving (3110003) Chapter – 5: Functions

Example of function definition:

int div(int a, int b) Function header


{
int result;
if (b==0)
printf(“Error! can’t divide by zero”};
else Function body
result=a/b;
return result;
}

• 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.

3. PROTOTYPES OF FUNCTION (OR FUNCTION DECLARATION)


• Like variable, before using a function in a program it can be declared. The
declaration of function is called as function prototyping.
• The function declaration follows following format.

return_type function_name(list of formal parameters);

• 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.

Example of function declaration:

#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:

int div(int a, int b);


OR
div(int a, int b);
OR
div(int, int);

• These all declarations are valid.


• The prototype of a function which doesn’t accept any parameters and doesn’t
return any value is written as follows:

void add(void);

• Prototype declaration is not essential but if it is not declared before it is used,


then the compiler assumes that details of that functions will be available at
linking time.

Prepared by – Prof. Viral H. Panchal 6


Programming for Problem Solving (3110003) Chapter – 5: Functions

4. CALLING A FUNCTION
• To use defined function, me must call it.
• Following syntax is used to call a function.

function_name(list of actual parameters);

• Before calling any function, it should be either declared or defined first and then
function call be made, otherwise compiler will generate error.

Calling function and called function:


• The function which calls another function is referred to as calling function and
the function which gets called is referred to as called function.

Actual and formal parameters:


• Parameters used in function call are referred to as actual parameters
whereas parameters used in function definition and function declaration
referred to as formal parameters.

Example:

/* Write a program to find greater number using function */

#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);
}
}

Prepared by – Prof. Viral H. Panchal 7


Programming for Problem Solving (3110003) Chapter – 5: Functions

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.

5. PARAMETER PASSING TO FUNCTION


• There are two ways to pass parameters to a function.
1. Call by value
2. Call by reference

5.1. Call by Value


• In this method, the contents of the arguments in the calling functions are not
changed, even if they are changed in the called function.
• The contents of the actual parameters get copied into the corresponding formal
parameters.
• The following program illustrates the concepts of call by value method.

/* Swapping of two numbers using call by value */

#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;

Prepared by – Prof. Viral H. Panchal 8


Programming for Problem Solving (3110003) Chapter – 5: Functions

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.

5.2. Call by Reference


• In this method, the contents of the arguments in the calling functions get changed,
i.e., the original values are changed.
• Instead of passing value of a variable, we can pass the memory address of the
variable to the function. This is called call by reference.
Prepared by – Prof. Viral H. Panchal 9
Programming for Problem Solving (3110003) Chapter – 5: Functions

• 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.

/* Swapping of two numbers using call by reference */

#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);

&a and &b pass the addresses of a and b.

Prepared by – Prof. Viral H. Panchal 10


Programming for Problem Solving (3110003) Chapter – 5: Functions

• This is shown below:

Contents of
a b  actual arguments
23 35
Address passed

37105 37120
x y  formal arguments
x points to a y points to b

• The function definition accepts the incoming addresses of a and b in the


corresponding pointers x and y.
• In the above figure, the addresses 37105 and 37120 might be something
different.
• By doing so we are able to return more than one value to the calling function,
which is not possible ordinarily by using a return statement.
• A return statement can return only a single value.

• 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).

Prepared by – Prof. Viral H. Panchal 11


Programming for Problem Solving (3110003) Chapter – 5: Functions

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:

1. Functions with no arguments and no return values


2. Functions with no arguments and return values
3. Functions with arguments and no return values
4. Functions with arguments and return values

6.1. Functions with No Arguments and No Return Values


• When a function does not have any arguments, we use void in the parenthesis.
And when a function does not return any value, void is written at the place of
return type.
• So, the general form of declaring the function with no return values and no
arguments is given below.
void function_name(void);

• 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);
}

Prepared by – Prof. Viral H. Panchal 12


Programming for Problem Solving (3110003) Chapter – 5: Functions

Output:
Addition Result: 5 + 45 = 50

6.2. Functions with No Arguments and Return Values


• When the function does not have any arguments, we use void in the parenthesis.
And when function return a value, the data type for that value is written in the
place of return type.
• So, the general form of declaring the function with return type but no arguments
is given below.
return_type function_name(void);

• To call the function with return type but no arguments, the following format is
used.
variable_name = function_name();

• variable_name is used to hold the value returned by the function. Empty


parenthesis indicates that the function does not have arguments.
• Example:

#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

Prepared by – Prof. Viral H. Panchal 13


Programming for Problem Solving (3110003) Chapter – 5: Functions

6.3. Functions with Arguments and No Return Values


• When the function does not return any value, void is written at the place of return
type. And when a function has arguments, these arguments are written within
parenthesis.
• So, the general form of declaring the function with arguments and no return
value is given below.
void function_name(argument list);

• To call the function with arguments and no return, the following format is used.
function_name(list of actual parameters);

• Every parameter is separated by comma in the list.


• Parameter list should match the order, type and number of parameters as given
in function prototype or definition.
• Example:

#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

6.4. Functions with Arguments and Return Values


• When the function has arguments and also returns a value, then it uses the
following form to declare the function.
return_type function_name(argument list);

Prepared by – Prof. Viral H. Panchal 14


Programming for Problem Solving (3110003) Chapter – 5: Functions

• To call the function with arguments and return value, the following format is used.
variable_name = function_name(list of actual parameters);

• variable_name is used to hold the value returned by the function.


• The type of variable should match the type of returned value.
• The function parameters in the list are separated by comma.
• Parameters in the list have same order, type and number of parameters as in the
prototype.
• Example:

#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

Prepared by – Prof. Viral H. Panchal 15


Programming for Problem Solving (3110003) Chapter – 5: Functions

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:

/* Program to illustrate the scope of variables */

#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);
}

Prepared by – Prof. Viral H. Panchal 16


Programming for Problem Solving (3110003) Chapter – 5: Functions

Output:
In main() function
a = 50
i = 20
In display() function
a = 50
j = 20
k = 35

Explanation:

• In this program, a is global variable so it can be accessed by both main()


and display() function.
• i is local variable of main() function so it is accessible only by main()
function itself.
• k and j are local variables of display() function.

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.

• A very simple example of recursion is given below:

#include<stdio.h>
#include<conio.h>
void main()
{
printf("\nThis is an example of recursion");
main();
}

Prepared by – Prof. Viral H. Panchal 17


Programming for Problem Solving (3110003) Chapter – 5: Functions

• 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

• Execution is terminated abruptly, otherwise the execution will continue


indefinitely.
• A commonly used example of a recursive procedure is finding the factorial of a
number.
• The factorial of a number n (denoted as n!) is defined as:

n! = n x (n-1) x (n-2) x .... x 1

which can be expressed as


n! = n x (n-1)!

/* Write a program to find factorial of a number using recursion */

#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);
}

Prepared by – Prof. Viral H. Panchal 18


Programming for Problem Solving (3110003) Chapter – 5: Functions

Output:
Enter a number for finding factorial: 6

Factorial of 6 = 720

/* Write a program to generate Fibonacci series upto given term


using recursion*/

#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

Prepared by – Prof. Viral H. Panchal 19


Programming for Problem Solving (3110003) Chapter – 5: Functions

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

Prepared by – Prof. Viral H. Panchal 20


Programming for Problem Solving (3110003) Chapter – 5: Functions

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:

#define MIN(a,b) ((a)<(b)?(a):(b))

• Here, MIN is the macro name.

• Let's see an example of #define to define a constant.


#include <stdio.h>
#define PI 3.14
void main()
{
printf("%f",PI);
}

Output:
3.140000

• Let's see an example of #define to create a macro.

#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));
}

Prepared by – Prof. Viral H. Panchal 21


Programming for Problem Solving (3110003) Chapter – 5: Functions

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.

C predefined macros example:

#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

Prepared by – Prof. Viral H. Panchal 22

You might also like