0% found this document useful (0 votes)
72 views59 pages

Functions and Recursions in C Programming

The document provides a comprehensive overview of functions and recursions in C programming, detailing their definitions, types, benefits, and syntax. It explains the distinction between library functions and user-defined functions, along with the structure of function declarations and definitions. Additionally, it covers concepts such as argument passing methods, including call by value and call by reference, and demonstrates how to pass arrays to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views59 pages

Functions and Recursions in C Programming

The document provides a comprehensive overview of functions and recursions in C programming, detailing their definitions, types, benefits, and syntax. It explains the distinction between library functions and user-defined functions, along with the structure of function declarations and definitions. Additionally, it covers concepts such as argument passing methods, including call by value and call by reference, and demonstrates how to pass arrays to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

FUNCTIONS &

RECURSIONS IN C
INTRODUCTION
▪ There are many situations where we might need to write same
line of code for more than once in a program which may lead
to repetition and bugs.
▪ C language provides an approach in which you can declare and
define a group of statements once in the form of a function and
it can be called and used whenever required.
DEFINITION

▪ A function is a block of code that performs a particular task.


▪ A function is a self-contained block of codes or sub programs
with a set of statements that perform some specific task or
coherent task when it is called. It is something like to hiring a
person to do some specific task like, every six months servicing
a bike and hand over to it.
▪ Any ‘C’ program contain at least one function i.e main().
TYPES OF FUNCTION
▪ C functions can be classified into two categories,
1) Library functions or Predefined functions–
• Library functions are those functions which are already defined in C
library, for example printf(), scanf() etc. Functions that can’t be
modified, it can only be read and used.
System defined function description:
□ Function definition : predefined, precompiled, stored in the library.
□ Function declaration(function prototype) : In header file.
□ Function call : By the programmer
USER DEFINED FUNCTIONS
• User-defined functions - The user defined functions are defined by
the user according to their requirement.

▪ A User-defined functions on the other hand, are those functions which


are defined by the user at the time of writing program.

▪ These functions are made for code reusability and for saving time and space.
BENEFITS OF FUNCTIONS
▪ It provides modularity to your program's structure.
▪ It makes your code reusable. Wherever required
the function can be called again and again.
▪ In case of large programs with thousands
of code lines,
▪ It makes the program more readable and easier to
understand.
SYNTAX : FUNCTION DECLARATION
returntype functionName(type1 parameter1, type2 parameter2,...);

▪ Like any variable or an array, a function must also be declared before its used.
▪ It's also called as Function Prototyping.
▪ Function declaration informs the compiler about the function name,
parameters it accepts, and its return type.
▪ The actual body of the function can be defined separately.
▪ Function declaration consists of 4 parts.
▪ returntype
▪ function name
▪ parameter list
▪ terminating semicolon
RETURN TYPE
▪ When a function is declared to perform some sort of calculation or any operation
and is expected to provide with some result at the end, in such cases, a return
statement is added at the end of function body.
▪ Return type specifies the type of value(int, float, char, double) that function is
expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be
void.
FUNCTION NAME
▪ Function name is an identifier and it specifies the name of the function. The
function name is any valid C identifier and therefore must follow the same
naming rules like other variables in C language.

PARAMETER LIST
▪ The parameter list declares the type and number of arguments that the function
expects when it is called. Also, the parameters in the parameter list receives the
argument values when the function is called. They are often referred as formal
parameters.
SYNTAX : Function definition

▪ Function definition consists of the whole description and code of the function. It
tells about what function is doing what are its inputs and what are its output
▪ It consists of two parts function header and function body.

returntype functionName(type1 parameter1, type2 parameter2,...)


{ Local variable declaration;
Statement 1; Statement 2;
Return value }
▪ The first line returntype functionName(type1 parameter1, type2 parameter2,...) is
known as function header and the statement(s) within curly braces is called
function body.
FUNCTION BODY
The function body contains the declarations and the statements(algorithm)
necessary for performing the required task. The body is enclosed within
curly braces { ... } and consists of three parts.
❑ local variable declaration(if required).
❑ function statements to perform the task inside the function.
❑ a return statement to return the result evaluated by the
function(if return type is void, then no return statement is
required).
CALLING A FUNCTION

▪ When a function is called, control of the program gets


transferred to the function.
functionName(argument1, argument2,...);
▪ The argument that are used inside the function call are called
actual argument or parameters.
ACTUAL ARGUMENTS
▪ The arguments which are mentioned or used inside the function
call is known as actual argument and copy of these are sent to the
called function.
▪ It can be written as constant, expression or any function call like
Function (x);
Example :
Function (20, 30);
Function (a*b, c*d);
Function(2,3,sum(a, b));
FORMAL ARGUMENTS
▪ The arguments which are mentioned in function definition are
called formal arguments or dummy arguments.
▪ These arguments are used to just hold the copy of the values that
are sent by the calling function through the function call.

▪ These arguments are like other local variables which are created
when the function call starts and destroyed when the function
ends.
Formal argument and the actual argument
1) The value(s) of the actual parameters are copied to formal parameters
when the call to that function is made.

2) The formal argument are automatically initialized when the copy of


actual arguments are passed while other local variable are assigned values
through the statements.

3) Order number and type of actual arguments in the function call


should match with the order number and type of the formal arguments
EXAMPLE for FUNCTION
#include<stdio.h> int sum(int x1,int y1)
int sum (int a1, int a2); {
main() int z=x1+y1;
{ return z;
int a,b; }
printf(“enter two no”);
scanf(“%d%d”,&a,&b);
int s=sum(a,b);
printf(“summation is = %d”,s);
}
NOTE
1. Any function can be called by another function even main()
can be called by other function.
2. Every function in a program must be
called directly or indirectly by the main()
function.
3. A function can be called any number of times.
4. A function can be defined within
another function, but scope will be local to that
function.
FUNCTION CATEGORIES
Functions are categorized based on argument passing and
return type
1. Functions with no argument and no return value
2. Functions with no argument with return value.
3. Function with argument but no return value.
4. Function with argument and return value.
Function with no argument and no return value
□ In this category, the function has no arguments.
□ It does not receive any data from the calling function.
Similarly, it doesn’t return any value.
□ The calling function doesn’t receive any data from the called
function. So, there is no communication between calling and
called functions.
Exampl
e
#include<stdio.h> void greatNum() // function definition
{
void greatNum(); // function declaration int i, j;
int main() printf("Enter 2 numbers that you
{ want to compare...");
greatNum(); // function call
return 0; scanf("%d%d", &i,
&j); if(i > j)
} printf("The greater number is: %d",
i); else
printf("The greater number is: %d",
} j);
Functions with arguments, no return values
□ In this category, function has some arguments . It receives
data from the calling function, but it doesn’t return a value
to the calling function.
□ The calling function doesn’t receive any data from the called
function. So, it is one way data communication between
called and calling functions.
Exampl
e#include<stdio.h>
void greatNum(int x, int y) // function definition
void greatNum(int a, int b); // function {
declaration if(x > y) {
printf("The greater number is: %d", x);
int main() }
{ else {
int i, j; printf("The greater number is: %d", y);
printf("Enter 2 numbers that you want }
to compare..."); }
scanf("%d%d",
greatNum(i, j); &i, &j);call
// function
return 0;
}
Functions with arguments and return values
□ In this category, functions has some arguments and it
receives data from the calling function.
□ Simillarly, it returns a value to the calling function. The
calling function receives data from the called function. So, it
is two-way data communication between calling and called
functions.
Exampl
e int greatNum(int x, int y) // function definition
#include<stdio.h> {
int greatNum(int a, int b); // function declaration if(x > y)
int main() {
return x;
{
}
int i, j, result;
else
printf("Enter 2 numbers that you want to {
compare..."); return y;
scanf("%d%d", &i, &j); }
result = greatNum(i, j); // function call }
printf("The greater number is: %d",
result);
return 0;
}
Functions with no arguments and return value
□ In this category, the functions has no arguments and it
doesn’t receive any data from the calling function, but it
returns a value to the calling function.
□ The calling function receives data from the called function.
So, it is one way data communication between calling and
called functions.
example
int greatNum() // function definition
#include<stdio.h>
{
int greatNum(); // function declaration
int i, j, greaterNum;
int main() printf("Enter 2 numbers that you want to
{ compare...");
scanf("%d%d", &i, &j);
int result;
if(i > j)
result = greatNum(); // function call {
printf("The greater number is: greaterNum = i;
%d", result); }
else
return 0;
{
} greaterNum = j;
}
// returning the result
return greaterNum;
}
Nesting functions
▪ C language also allows nesting of functions i.e to use/call one function inside another
function's body. We must be careful while using nested functions, because it may lead to
infinite nesting.
Example :
function1()
{
// function1 body here
function2();
// function1 body here
}
If function2() also has a call for function1() inside it, then in that case, it will lead to an infinite
nesting. They will keep calling each other and the program will never terminate.
Call by value and call by reference
▪ There are two way through which we can pass the arguments to the
function such as call by value and call by reference.
Call by value
▪ In the call by value copy of the actual argument is passed to
the formal argument and the operation is done on formal
argument.
▪ When the function is called by ‘call by value’ method, it
doesn’t affect content of the actual argument.
▪ Changes made to formal argument are local to block of called
function so when the control is back to calling function the
changes made is vanish.
A:totcmcnt
culling function
my func.
Tnitizlly

vall is 10
10
create a copy of
1? vml 1 and vmw

void myfunc(x, y)
my flnr()
x — 40,’ vvnrkm on the
copy ot vaI1
and va2
Example
#include<stdio.h> void change(int a,int b)
void change(int a,int {
b); int main() int k;
{
int x,y; k=a;
//change(int a,int b); a=b;
printf("enter two values:\ b=k;
n"); scanf("%d%d",&x,&y); }
change(x ,y);
printf("value of x=%d and y=%d\n",x ,y);
}
Call by reference
□ Instead of passing the value of variable, address or
reference is passed and the function
operate on address of the variable rather than
value.
□ Here formal argument is alter to the actual
argument, it means formal arguments calls the
actual arguments.
Example : swapping two numbers

#include<stdio.h void change(int *a, int *b)


> void main() {
{ int k;
int a,b; k=*a;
change(int *,int*); *a=*b;
printf("enter two values:\ *b= k;
n"); scanf("%d printf("value in this function a=
%d",&a,&b); %d and b=%d\n",*a,*b);
change(&a,&b); }
printf("after changing two value
of a=%d and b=%d\n:",a,b);
}
Passing arrays as function arguments in C
For one-dimensional array:
□ There are multiple ways to pass one-dimensional arrays as arguments
in C.
□ We need to pass the array to a function to make it accessible within
the function. If we pass an entire array to a function, all
the elements of the array can be accessed within the function.
□ Single array elements can also be passed as arguments. This can
be done in exactly the same way as we pass variables to a
function.
Passing single element of an array to a function

#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()
{
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element ageArray[2]only.
}
Passing address of element of an array
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
Passing entire array to function
□ When passing an entire single dimensional array to a function, a
formal parameter must be used to accept the array. This can be
done in one of the following ways:
1. Passing the address of the array elements
2. Passing the entire array with the array size
3. Passing the entire array without mentioning the array size
Passing the address of the array
elements
□A pointer can be passed with a help of
a pointer variable carrying the address of the first
location of the array.
□ Ex:
void myFunction(int *param) { /* function body */ }

□ This type of array passing mechanism is


called call by reference.
□ In this case, we pass the address of the array elements while
calling the function.
#include <stdio.h>
void myfuncn( int *var1, int var2)
{
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Passing entire array with and without mentioning size
□ Ex: without mentioning the size.
void myFunction(int param[]) { /* function body }

□ Ex: with mentioning the size.


void myFunction(int param[100]) { /* function
body }
#include<stdio.h>

float findAverage(int marks[]);

int main() float findAverage(int


{ marks[])
float avg;
int marks[] = {99, 90, 96, 93, 95}; {
avg = findAverage(marks); int i, sum = 0;
// name of the array is passed as argument. float avg;
printf("Average marks = %.1f", avg);
return 0; for (i = 0; i <= 4; i++)
} { sum += marks[i];
}
avg = (sum /
5); return avg;
}
Passing multi dimensional array
□ 2D array
□ We can pass single element of an array or entire array.
□ While passing entire 2d array column size must be
specified.
#include<stdio.h> void displayArray(int arr[3][3])
void displayArray(int arr[3][3]); {
int main() int i, j;
{ printf("The complete array is: \n");
int arr[3][3], i, j; for (i = 0; i < 3; ++i)
printf("Please enter 9 numbers for the {
array: \n"); // getting cursor to new line
for (i = 0; i < 3; ++i) printf("\n");
{ for (j = 0; j < 3; ++j)
for (j = 0; j < 3; ++j) {
{ // \t is used to provide tab space
scanf("%d", &arr[i][j]); printf("%d\t", arr[i][j]);
} }
} }
// passing the array as argument }
displayArray(arr);
return 0;
}
RECURSION IN C
Introduction
• The process of calling a function by itself is called recursion and the
function which calls itself is called recursive function.
• Recursion is used to solve various mathematical problems by
dividing it into smaller problems. This method of solving a problem is
called Divide and Conquer.

Note: In order to prevent infinite recursive call, we need to define proper


exit condition in a recursive function.
Syntax of recursive function
Flowchart of recursion
Types of recursion
• There are two types of recursion : Direct and indirect.
Direct recursion
When in the body of a method there is a call to the same method, we say that the
method is directly recursive. That means Direct recursion occurs when a
method invokes itself.
Indirect recursion
If method A calls method B, method B calls method C, and method C calls
method A we call the methods A, B and C indirectly recursive or mutually
recursive.
Indirect recursion occurs when a method invokes another method, eventually
Example : infinite recursive function

• In this program, we are calling main() from main() which is recursion.


• But we haven't defined any condition for the program to exit. Hence this
code will print "Hello world" infinitely in the output screen.
Example : sum of natural number
#include <stdio.h> int sum(int num)
int sum(int n); {
int main() if (num!=0)
return num + sum(num-1);
{
else
int number, result; return num;
printf("Enter a positive }
integer: "); scanf("%d",
&number);
result = sum(number);
printf("sum=%d", result);
Example : factorial using recursion
#include<stdio.h> int main()
int factorial(int n) {
int num,f;
{
printf("Enter a number: ");
if(n==0) scanf("%d",&num);
return 1; f=factorial(num);
else printf("Factorial of %d = %d",num,f);
return (factorial(n-1)*n); return 0;
}
}
Example: Fibonacci number
#include<stdio.h> int main()
{
int i,n;
int fibo(int num) printf("Enter the required
{ term: "); scanf("%d",&n);
if(num==1||num==2) printf("First %d fibonacci numbers
return 1; are\n",n);
for (i=1; i<=n; i++)
else printf("%d\n",fibo(i));
return return 0;
(fibo(num-1)+fibo(num-2)); }
// recursive call
}
Advantages of recursion

• Using recursion many complex mathematical problems can be solved


easily.
• Using recursion, a problemcan be solved in
less number of programming construct, compared to its
iterative counterpart.
Disadvantages of recursion
• Recursive programs are generally slower than non recursive programs
because it needs to make a function call so the program must save all its
current state and retrieve them again later. This consumes more time
making recursive programs slower.
• Recursive programs requires more memory to hold intermediate states in
a stack. Non recursive programs don't have any intermediate states, hence
they don't require any extra memory.
• Recursive programs may crash due to stack overflow (memory shortage)
errors.
• Bugs in a recursive function are difficult to trace and remove.
Assignment for Function & Recursions
1. Write a c program to read characters from an array and display its ascii value, using functions.
2. Write a C program to print all natural numbers in reverse from n to 1 using recursive function.
3. Write a recursive C function find the sum of digits of a number.
4. Write a recursive C function find GCD of two numbers.
5. Write a C program to reverse a sentence using recursive function
6. Write a C program to display prime numbers between intervals using function.
7. Write a C program to find the Largest number among three numbers using function.
8. Write a C program to find factorial of a number using function.
9. Write a program in C to find the sum of the series 1!/1+2!/2+3!/3+4!/4+5!/5 using the
function by passing appropriate parameters and return value.

10. Write a C program to convert decimal number to binary using functions.

11. Write a C program to swap two numbers by passing appropriate parameters to the
function.
Useful link

• [Link]
i
ng/[Link]

You might also like