0% found this document useful (0 votes)
16 views17 pages

Unit-III PART-I

This document provides an overview of functions in C programming, detailing their definition, advantages, syntax, types, and how they operate. It explains the concepts of function declaration, definition, calling, return types, and parameter passing methods, including pass by value and pass by reference. Additionally, it covers recursion and how arrays can be passed to functions, emphasizing the importance of modularity and code reusability in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views17 pages

Unit-III PART-I

This document provides an overview of functions in C programming, detailing their definition, advantages, syntax, types, and how they operate. It explains the concepts of function declaration, definition, calling, return types, and parameter passing methods, including pass by value and pass by reference. Additionally, it covers recursion and how arrays can be passed to functions, emphasizing the importance of modularity and code reusability in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

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

There are the following advantages of C functions.

 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

The syntax of function can be divided into 3 aspects:

1. Function Declaration
2. Function Definition
3. Function Calls

1. Function Declarations: A function must be declared globally in a c program to tell the


compiler about the function name, function parameters, and return type. In a function
declaration, we must provide the function name, its return type, and the number and type of
its parameters. A function declaration tells the compiler that there is a function with the given
name defined somewhere else in the program.

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

int sum(int a, int b);


int sum(int , int);

Note: A function in C must always be declared globally before calling it.

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.

return_type function_name (para1_type para1_name, para2_type para2_name)


{
// body of the function
}
3. Function Call: A function call is a statement that instructs the compiler to execute the
function. We use the function name and parameters in the function call.

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:

// C program to show function

// call and definition

#include <stdio.h>

// Function that takes two parameters

// a and b as inputs and returns

// their sum

int sum(int a, int b)

return a + b;

// Driver code

int main()

// Calling sum function and

// storing its value in add

variable int add = sum(10, 30);

printf("Sum is: %d", add);

return 0;

Output

Sum is: 40.

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:

int function_name(int var1, int var2);

Conditions of Return Types and Arguments

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.

1. Function with no arguments and no return value


2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value.
How Does C Function Work?

Working of the C function can be broken into the following steps as mentioned below:

1. Declaring a function: Declaring a function is a step where we declare a function.


Here we define the return types and parameters of the function.
2. Defining a function:
3. Calling the function: Calling the function is a step where we call the function by
passing the arguments in the function.
4. Executing the function: Executing the function is a step where we can run all the
statements inside the function to get the final result.
5. Returning a value: Returning a value is the step where the calculated value after the
execution of the function is returned. Exiting the function is the final step where all
the allocated memory to the variables, functions, etc is destroyed before giving full
control to the main function.

Types of Functions

There are two types of functions in C:

1. Library Functions
2. User Defined Functions

1. Library Function

A library function is also referred to as a “built-in function”. A compiler package already


exists that contains these functions, each of which has a specific meaning and is included in
the package. Built-in functions have the advantage of being directly usable without being
defined, whereas user-defined functions must be declared and defined before being used.
For Example:

pow(), sqrt(), strcmp(), strcpy() etc.

Advantages of C library functions

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

Advantages of User-Defined Functions

 Changeable functions can be modified as per need.


 The Code of these functions is reusable in other programs.
 These functions are easy to understand, debug and maintain.

Example:

// C program to show
// user-defined functions #include <stdio.h>

int sum(int a, int b)


{
return a + b;
}
// Driver code int main()
{
int a = 30, b = 40;
// function call
int res = sum(a, b); printf("Sum is: %d", res); return 0;
}
Output
Sum is: 70
Passing Parameters to Functions:

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.

We can pass arguments to the C function in two ways:

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>

void swap(int var1, int var2)


{
int temp =
var1; var1 =
var2; var2 =
temp;
}
// Driver
code int
main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",var1,
var2); swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}
Output

Before swap Value of var1 and var2 is: 3,

2 After swap Value of var1 and var2 is: 3,


2. Pass by Reference

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:

// C program to show use of


// call by
Reference
#include <stdio.h>
void swap(int *var1, int *var2)
{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
// Driver
code int
main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\
n", var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",var1, var2);
return 0;
}

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:

int sum(int k);


int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}

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.

In the following example, recursion is used to calculate the factorial of a number.

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.

Pseudocode for writing any recursive function is given below.

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.

You might also like