[go: up one dir, main page]

0% found this document useful (0 votes)
21 views14 pages

Unit 5

The document discusses functions in C programming. It defines functions and describes the different types of functions. It also explains function declaration, definition, call, return values, categories of functions with examples. Furthermore, it covers call by value vs call by reference and recursion in functions.

Uploaded by

mananpatel143414
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)
21 views14 pages

Unit 5

The document discusses functions in C programming. It defines functions and describes the different types of functions. It also explains function declaration, definition, call, return values, categories of functions with examples. Furthermore, it covers call by value vs call by reference and recursion in functions.

Uploaded by

mananpatel143414
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/ 14

UNIT 5 Functions

PREPARED BY
PROF. VISHVA UPADHYAY
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

What is Function?
● A function is a block of code that performs a specific task.
● We can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the C program.

Advantage of functions in C
● By using functions, we can avoid rewriting the same logic/code again and again in a
program.
● We can call C functions any number of times in a program and from any place in a
program.
● We can track a large C program easily when it is divided into multiple functions.
● Reusability is the main achievement of C functions.
● However, Function calling is always overhead in a C program.

Types of the Function


Functions are broadly classified into two types which are as follows −
● predefined functions
● user defined functions

Predefined (or) library functions


● These functions are already defined in the system libraries.
● These are the functions which are declared in the C header files such as scanf(), printf(),
gets(), puts(), ceil(), floor() etc.
● Programmers can reuse the existing code in the system libraries which is helpful to write
error free code.
● Users must be aware of syntax of the function.

User defined functions


● These functions must be defined by the programmer or user.
● Programmers have to write the coding for such functions and test them properly before
using them.
● The syntax of the function is given by the user so there is no need to include any header
files.

Function Declaration
● A function must be declared globally in a c program to tell the compiler about the
function name, function parameters, and return type.
Syntax:

2
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

return_type function_name (argument list);


Function Definition
● It contains the actual statements which are to be executed. It is the most important aspect
to which the control comes when the function is called.only one value can be returned
from the function.
Syntax:
return_type function_name (argument list) {function body;}

Function Call
● Function can be called from anywhere in the program. The parameter list must not differ
in function calling and function declaration. We must pass the same number of functions
as it is declared in the function declaration.
Syntax:
function_name (argument_list)

Return Value
● A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.

Category of Functions
● function without arguments and without return value
● function without arguments and with return value
● function with arguments and without return value
● function with arguments and with return value

Example for Function without argument and return value


#include<stdio.h>
void sum();
void main()
{
printf("\n sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);

3
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

printf("The sum is %d",a+b);


}
Output
sum of two numbers:
Enter two numbers 10
24
The sum is 34

Example for Function without argument and with return value

#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nsum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
sum of two numbers:
Enter two numbers 10
24
The sum is 34

Example for Function with argument and without return value

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nsum of two numbers:");
printf("\nEnter two numbers:");

4
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output
sum of two numbers:
Enter two numbers 10
24
The sum is 34

Example for Function with argument and with return value

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nsum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output
sum of two numbers:
Enter two numbers:10
20
The sum is : 30

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by value and call
by reference.

5
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

Call by value in C
● In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
● In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
● In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
● The actual parameter is the argument which is used in the function call whereas the
formal parameter is the argument which is used in the function definition.

#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);

swap(a,b);

printf("After swapping values in main a = %d, b = %d\n",a,b)


}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

6
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

Call by reference in C
● In call by reference, the address of the variable is passed into the function call as the
actual parameter.
● The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
● In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored at
the address of the actual parameters, and the modified value gets stored at the same
address.

#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);

swap(&a,&b);

printf("After swapping values in main a = %d, b = %d\n",a,b);


void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Difference between call by value and call by reference in c

Call by value Call by reference

7
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

A copy of the value is passed into the An address of value is passed into the
function function

Changes made inside the function is Changes made inside the function validate
limited to the function only. The outside of the function also. The values of
values of the actual parameters do not the actual parameters do change by
change by changing the formal changing the formal parameters.
parameters.

Actual and formal arguments are Actual and formal arguments are created at
created at the different memory the same memory location
location

Recursion
● Any function which calls itself is called a recursive function, and such function calls are
called recursive calls.
● It is important to impose a termination condition of recursion.
● Recursion cannot be applied to all the problem, but it is more useful for the tasks that can
be defined in terms of similar subtasks. For Example, recursion may be applied to
sorting, searching, and traversal problems.

Advantages of recursion
1. The code may be easier to write.
2. To solve such problems which are naturally recursive such as the tower of Hanoi.
3. Reduce unnecessary calling of function.
4. Extremely useful when applying the same solution.
5. Recursion reduces the length of code.
6. It is very useful in solving the data structure problem.
7. Stacks evolutions and infix, prefix, postfix evaluations etc.

Disadvantages of recursion
1. Recursive functions are generally slower than non-recursive functions.
2. It may require a lot of memory space to hold intermediate results on the system stacks.
3. Hard to analyze or understand the code.
4. It is not more efficient in terms of space and time complexity.
5. The computer may run out of memory if the recursive calls are not properly checked.
Example
recursion is used to calculate the factorial of a number.
#include <stdio.h>
int fact (int);
int main()

8
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Output
Enter the number whose factorial you want to calculate?5
factorial = 120

find the nth term of the Fibonacci series.

#include<stdio.h>
int fibonacci(int);
void main ()

9
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}

Output
Enter the value of n?12
144

What are Macros in C language?


● The macro in C language is known as the piece of code which can be replaced by the
macro value. The macro is defined with the help of #define preprocessor directive and the
macro doesn’t end with a semicolon(;).
● Macro is just a name given to certain values or expressions, it doesn't point to any
memory location.
● Whenever the compiler encounters the macro it replaces the macro name with the macro
value. Two macros could not have the same name.
The syntax of the macro is as shown in the following figure. Here we will have the 3
components:

1. #define - Preprocessor Directive


2. PI - Macro Name

10
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

3. 3.14 - Macro Value

#include<stdio.h>

// This is macro definition


#define PI 3.14

void main()
{
// declaration and initialization of radius
int radius = 5;
// declaration and calculating the area
int area = PI * (radius*radius);

// Printing the area of circle


printf("Area of circle is %d", area);
}

Output:
Area of circle is 78.500000

● We defined the PI constant as a macro with the value 3.14.


● Here the macro name PI at the 11th line got replaced with the macro value 3.14 as we
saw in the definition and we got the area of a circle as the output.
● This replacement of value occurs due the to preprocessor and preprocessor directive
#define.

Predefined Macros

1 __DATE__
The current date as a character literal in "MMM DD YYYY" format.

2 __TIME__
The current time as a character literal in "HH:MM:SS" format.

3 __FILE__
This contains the current filename as a string literal.

4 __LINE__
This contains the current line number as a decimal constant.

5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.

11
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

#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("ANSI :%d\n", __STDC__ );

}
File :test.c
Date :Jun 4 2022
Time :03:36:24
Line :8
ANSI :1

Pre-processing
● Whenever we write a certain code in C language it goes under the process of compilation
where it gets converted from source code to machine understandable code.
● But before the compilation process, the source code goes through preprocessing which is
done by the preprocessor.
● The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process.

12
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

● If there are some preprocessing directives found then certain actions are taken on them by
the preprocessor.
● There are multiple types of preprocessors such as #define, #if, #error, #warning etc.,
They all start with the # symbol.
● To define the macro we use the #define a preprocessing directive which performs the
action to replace the macro name with the macro value at the time of preprocessing.

preprocessor directives

1 #define
Substitutes a preprocessor macro.

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.

6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.

8 #elif
#else and #if in one statement.

9 #endif
Ends preprocessor conditional.

10 #error
Prints error message on stderr.

11 #pragma
Issues special commands to the compiler, using a
standardized method.

13
AHMEDABAD INSTITUTE OF TECHNOLOGY PPS(3110003)

14

You might also like