Unit-III PART-I
Unit-III PART-I
FUNCTIONS
Function:
A function in C is a set of statements that when called perform some specific task. It is the
basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces, having certain
meanings and performing certain operations. They are also called subroutines or procedures
in other languages.
Advantage of functions in C
By using functions, we can avoid rewriting 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 a overhead in a C program.
Syntax of Functions in C
1. Function Declaration
2. Function Definition
3. Function Calls
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.
Example
2. Function Definition:
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.
A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly. The
below example serves as both a function definition and a declaration.
In the below example, the first sum function is called and 10,30 are passed to the sum
function. After the function call sum of a and b is returned and control is also returned back
to the main function of the program.
Note: Function call is neccessary to bring the program control to the function definition. If
not called, the function statements will not be executed.
Example of C Function:
#include <stdio.h>
// their sum
return a + b;
// Driver code
int main()
return 0;
Output
As we noticed, we have not used explicit function declaration. We simply defined and
called the function.
Function Return Type
Function return type tells what type of value is returned after all function is executed. When
we don’t want to return a value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the function.
Note: Only one value can be returned from a C function. To return multiple values, we have to
use pointers or structures.
Function Arguments
Function Arguments (also known as Function Parameters) are the data that is passed to a
function.
Example:
In C programming language, functions can be called either with or without arguments and
might return values. They may or might not return values to the calling functions.
Working of the C function can be broken into the following steps as mentioned below:
Types of Functions
1. Library Functions
2. User Defined Functions
1. Library Function
C Library functions are easy to use and optimized for better performance.
C library functions save a lot of time i.e, function development time.
C library functions are convenient as they always work.
Example:
// C program to implement
// the above approach #include <math.h> #include <stdio.h>
// Driver code int main()
{
double Number; Number = 49;
// Computing the square root with
// the help of predefined C
// library function
double squareRoot = sqrt(Number);
printf("The Square root of %.2lf = %.2lf", Number, squareRoot); return 0;
}
Output
The Square root of 49.00 = 7.00
2. User Defined Function
Functions that the programmer creates are known as User-Defined functions or “tailor-made
functions”. User-defined functions can be improved and modified according to the need of
the programmer. Whenever we write a function that is case-specific and is not defined in any
header file, we need to declare and define our own functions according to the syntax.
Example:
// C program to show
// user-defined functions #include <stdio.h>
The data passed when the function is being invoked is known as the Actual parameters. In the
below program, 10 and 30 are known as actual parameters. Formal Parameters are the
variable and the data type as mentioned in the function declaration. In the below program, a
and b are known as formal parameters.
1. Pass by Value
2. Pass by Reference
1. Pass by Value
Parameter passing in this method copies values from actual parameters into formal function
parameters. As a result, any changes made inside the functions do not reflect in the caller’s
parameters.
// C program to show use
// of call by value
#include
<stdio.h>
The caller’s actual parameters and the function’s actual parameters refer to the same locations,
so any changes made inside the function are reflected in the caller’s actual parameters.
Example:
Output
Recursion:
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and
such function calls are called recursive calls. Recursion involves several numbers of recursive
calls. However, it is important to impose a termination condition of recursion. Recursion code
is shorter than iterative code however it is difficult to understand.
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.
Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively.
However, some problems are best suited to be solved by the recursion, for example, tower of
Hanoi, Fibonacci series, factorial finding, etc.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers together
by breaking it down into the simple task of adding two numbers:
Example:
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller
than k and returns the result. When k becomes 0, the function just returns 0. When running,
the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns
the result.
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure given
below:
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is returned from the function.
The case at which the function doesn't recur is called the base case whereas the instances
where the function keeps calling itself to perform a subtask, is called the recursive case. All
the recursive functions can be written using this format.
1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Pass Array to Functions in C
In C, the whole array cannot be passed as an argument to a function. However, you can
pass a pointer to an array without an index by specifying the array’s name.
Arrays in C are always passed to the function as pointers pointing to the first element of the
array.
Syntax
In C, we have three ways to pass an array as a parameter to the function. In the function
definition, use the following syntax:
return_type foo ( array_type array_name[size], ...);
Mentioning the size of the array is optional. So the syntax can be written as:
return_type foo ( array_type array_name[], ...);
In both of the above syntax, even though we are defining the argument as array it will still
be passed as a pointer. So we can also write the syntax as:
return_type foo ( array_type* array_name, ...);
But passing an array to function results in array decay due to which the array loses
information about its size. It means that the size of the array or the number of elements of
the array cannot be determined anymore. To explore how functions and arrays work
together in complex data structures, the C Programming Course Online with Data
Structures offers in-depth explanations and examples.
// C program to pass
the array as a function
and check its size
#include <stdio.h>
#include <stdlib.h>
//voidfun(int*arr)orvo)
void func(int arr[8])
{
printf("Size of arr[]
in func(): %d bytes",
sizeof(arr));
}
// Drive code
int main()
{
int arr[8] = { 1, 2, 3,
4, 5, 6, 7, 8 };
printf("Size of arr[]
in main(): %dbytes\n",
sizeof(arr));
func(arr);
return 0;
}
Output
Size of arr[] in main(): 32bytes
Size of arr[] in func(): 8 bytes
As we can see,
The size of the arr[] in the main() function (where arr[] is declared) is 32 bytes which is =
sizeof(int) * 8 = 4 * 8 = 32 bytes.
But in the function where the arr[] is passed as a parameter, the size of arr[] is shown as
8 bytes (which is the size of a pointer in C).
It is due to the fact that the array decays into a pointer after being passed as a parameter.
One way to deal with this problem is to pass the size of the array as another parameter to
the function.