0% found this document useful (0 votes)
2 views

C Programming Module-VIII

The document outlines the concepts of functions in C programming, including their declaration, definition, and types such as user-defined and predefined functions. It explains parameter passing techniques like call by value and call by reference, along with examples of recursion and limitations of recursive functions. Additionally, it emphasizes the importance of functions in structured programming and modularity.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C Programming Module-VIII

The document outlines the concepts of functions in C programming, including their declaration, definition, and types such as user-defined and predefined functions. It explains parameter passing techniques like call by value and call by reference, along with examples of recursion and limitations of recursive functions. Additionally, it emphasizes the importance of functions in structured programming and modularity.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

C PROGRAMMING
Functions

B.Tech. – CSE
Academic Year : 2023-24
Term – II
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 1
Professor, Dept. of CSE, AU
OUT LINE

Functions

Designing structured programs

Declaring a function

Signature of a function

Parameters and return type of a function

Passing parameters to functions

Call by value

Passing arrays to functions

Passing pointers to functions

Idea of call by reference

Some C standard functionsCompiled


and libraries
by Er. K. Ravikanth, Assistant
1/27/2025 2
Professor, Dept. of CSE, AU
Contd
OUT LINE

Recursion

 Simple programs

 Finding Factorial

 Fibonacci series

 Limitations of Recursive functions

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 3
Professor, Dept. of CSE, AU
What is Function

 A function is self contained block designed to perform a specific task.

 A C program must have at least one function. i.e. main( ).

 A function perform a modular programming.

 A function in programming is a reusable block of code that makes a


program easier to test, understand and can be modified easily without
changing the calling program.

main( )
{
// Block of statements
}
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 4
Professor, Dept. of CSE, AU
Designing structured programs

A structured program comprised of


1.Function Declaration
2.Function Definition
3.Function call

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 5
Professor, Dept. of CSE, AU
Function Declaration
 Before using any function in C, we must declare that function as per its
syntax.

Syntax:

Return Type Function Name( type1 arg1, typ2 ar2,…….type-n arg-n)

Eg:

int add( int a, int b);

float power(float base, int exponent);

Note: Argument names are optional i.e.

Return Type Function Name( type1, typ2,...type-n);

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 6
Professor, Dept. of CSE, AU
Function Definition
 A function definition consists of the whole decryption
and code of a function.

1.Function name

2.Function return type

3.List of parameters

4.Local variable declarations

5.Function statements

6.A return statement


Compiled by Er. K. Ravikanth, Assistant
1/27/2025 7
Professor, Dept. of CSE, AU
 All the six elements are grouped into two parts

1.Function Header

(Function name, function return type, list of parameters)

2.Function Body

(Local variable declarations, Function statements, return statements)

General Format of a function:

Return type function name(parameter list)

Local variable declarations;

Executable statement1;

-----------------------

-----------------------

Retrun type

} Compiled by Er. K. Ravikanth, Assistant


1/27/2025 8
Professor, Dept. of CSE, AU
Function Call
• Function call is a statement which is used to execute the function
definition body where ever it requires.
• We call a function using function call statement in any number of times.
• How user defined function works:
void main()
{
return type function (list of argument types);-----------Function
prototype
---------------
---------------
var=functionName(actual parameters)--------------------Function call
}
Return type function name(formal parameters)------Function
definition
-------------
-------------
Return statement;
}
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 9
Professor, Dept. of CSE, AU
Contd…

Whenever a function call statement executed

 Actual parameter values copied into formal parameters.

 The execution will jump to functions definition body.

 After completion of executing all instructions in definition body, the control


will return back to the next statement after the function call.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 10
Professor, Dept. of CSE, AU
Parameter (Arguments)
• There are two types of parameters in C:

– Actual parameters are parameters as they appear in function calls.

– Formal parameters are parameters as they appear in function definition.


void main()
{
int n;
display(n);
}
void display(int x)
{
-----------
-----------
}

• x is “Formal Parameter“

• n is “Actual Parameter“
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 11
Professor, Dept. of CSE, AU
Types of Parameter Passing
• There are two ways to pass value or data to function in C
language: call by value and call by reference. Original value is
not modified in call by value but it is modified in call by
reference.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 12
Professor, Dept. of CSE, AU
Example (call by Value)
#include <stdio.h>
void swap(int, int);
void swap(int a, int b)
void main()
{
{ int temp;
int x, y; temp = b;
printf("Enter the value of x and y\n"); b = a;

scanf("%d%d",&x,&y); a = temp;

printf("Before Swapping\nx = %d\ny = %d\n", x, y); printf("Values of a and b is %d


%d\n",a,b);
swap(x, y);
}
printf("After Swapping\nx = %d\ny = %d\n", x, y);
}

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 13
Professor, Dept. of CSE, AU
Example (Call By Reference)
#include <stdio.h>
void swap(int *x, int *y);
void swap(int *x, int *y)
void main ()
{
{
int a = 100; int temp;
int b = 200; temp = *x;
printf("Before swap, value of a : %d\n", a ); *x = *y;
printf("Before swap, value of b : %d\n", b );
*y = temp;
swap(&a, &b);
}
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
}
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 14
Professor, Dept. of CSE, AU
No. Call by value Call by reference
1 A copy of value is passed to the An address of value is passed to the
function function

2 Changes made inside the Changes made inside the function is


function is not reflected on other reflected outside the function also
functions

3 Actual and formal arguments Actual and formal arguments will be


will be created in different created in same memory location
memory location

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 15
Professor, Dept. of CSE, AU
Parameter Passing Techniques
• In C program we can pass arguments from one function to another
function in two ways.

1.Call-by-Value

2.Call-by-Reference

Call-by-Value:

 In this actual parameter values are copied into the formal


parameters.

 Operation can be done on the formal parameters only.

 Note: If you made any changes on formal parameters that does not
reflect on the actual parameters.
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 16
Professor, Dept. of CSE, AU
void main()
{
int x=10, y=20;
clrscr();
void swap(int, int);
printf("x,y values before swapping:x=%d,y=%d",x,y);
swap(x,y);
printf("x,y values after swapping: x=%d,y=%d",x,y);
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
Output:
x,y values before swap:x=10, y=20
x,y values after swap:x=20, y=10
Note:
In the above program x,yCompiled
are actual parametrs
by Er. K. and a,b are formal/dummy parameters
Ravikanth, Assistant
1/27/2025 17
Professor, Dept. of CSE, AU
Call-by-Reference

 In this way instead of actual parameter values


,addresses are passing to the formal parameters.

 Operation can be done on the addresses rather than


values.

 Note: If you made any changes on formal parameters


that reflects on the actual parameters.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 18
Professor, Dept. of CSE, AU
void main()
{
int x=10, y=20;
clrscr();
void swap(int*, int*);
printf("x,y values before swapping:x=%d,y=%d",x,y);
swap(&x,&y);
printf("x,y values after swapping: x=%d,y=%d",x,y);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
x, y values before swap: x=10, y=20
x, y values after swap: x=20, y=10
Note:
In the above program x,y are actual parameters and a,b are formal/dummy parameters
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 19
Professor, Dept. of CSE, AU
Passing arrays to functions
void main()
{
int i, arr[10],n;
void display(*int, int);
clrscr();
printf("Enter the size of the Array:");
scanf("%d", &n);
printf("Enter the array elements");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
display(arr,n);
getch();
} Compiled by Er. K. Ravikanth, Assistant
1/27/2025 20
Professor, Dept. of CSE, AU
void display(int *ptr, int n)

int i;

printf("Printing array elements by calling display function only once");

for(i=0;i<n;i++)

printf("%d\t",*(ptr+i));

Output:

Enter the size of the Array: 6

Enter the array elements: 10 25 30 12 14 15

Printing array elements by calling display function only once: 10 25 30 12 14 15

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 21
Professor, Dept. of CSE, AU
Passing pointer to a function( Call-by-reference)
void main()
{
int x=10, y=20;
clrscr();
void swap(int*, int*);
printf("x,y values before swapping:x=%d,y=%d",x,y);
swap(&x,&y);
printf("x,y values after swapping: x=%d,y=%d",x,y);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
x, y values before swap: x=10, y=20
x, y values after swap: x=20, y=10
Note: In the above program x,y are actual parameters and a,b are formal/dummy parameters
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 22
Professor, Dept. of CSE, AU
Types of Functions
• We have two types of functions

1. User Defined functions

2. Predefined functions

Predefined functions:
E.g.: printf(),scanf(),pow(x,y), sqrt(n),ceil(),floor(),round()

User Defined functions:

Eg: swap(),display() etc and main()

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 23
Professor, Dept. of CSE, AU
Categories of user defined function
1.Function with return type and parameters.

Eg. int main(int a, int b);

2.Function without return type and parameters.

Eg: main(int a, int b);

3. Function with return type and without parameters.

Eg: int main();

4.Function without return type and without parameters.

Eg: main()

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 24
Professor, Dept. of CSE, AU
Recursion
Calling a function itself is called recursion

Eg: Factorial of given number 4

4!=4x3x2x1

4!=4x3!

3!=3x2!

2!=2x1!

1!=1x0!

0!=1

The execution order is as follows

4!=4x3! (6x4=24)

3!=3x2!(3x2=6)

2!=2x1!(2x1=2)

1!=1x0!(1x1=1)
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 25
Professor, Dept. of CSE, AU
Contd..

Program

void main() int factorial(int n)

int factorial(int); {

void main() if(n==0)

{ return 1;

int i,f; else

printf("Enter the number"); return(n*factorial(n-1))

scanf("%d",&n); }

f=factorial(n);

printf("%d",f);

}
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 26
Professor, Dept. of CSE, AU
Fibonacci Sequence using recursion
int fib(int);
void main()
{
int n,i;
clrscr();
printf("Enter the number");
scanf("%d",&d);
for(i=0;i<=n,i++)
{
printf("%d",fib(n));
}
getch();
}
int fib(int n)
{
if(n<=1)
return n;
else
return fib(n-1) + fib(n-2);
} 1/27/2025 Compiled by Er. K. Ravikanth, Assistant
27
Professor, Dept. of CSE, AU
Limitations of Recursion

1.Overhead due to repetitive steps.

2.Wastage of memory due allocation of memory for local


and forma variables each call.

3.Function requires termination due recursion i.e infinite


call.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 28
Professor, Dept. of CSE, AU
Function
• A function is a group of statements that together perform a task.
Every C program has at least one function, which is main().

• C functions are basic building blocks in a program

• You can divide up your code into separate functions.

• A function declaration tells the compiler about a function's name,


return type, and parameters.

• A function definition provides the actual body of the function

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 29
Professor, Dept. of CSE, AU
Types of functions in C programming

• There are two types of functions in C


programming:

• Standard library functions (inbuilt functions):


printf(), getch(), strlen(), clrscr().

• User defined functions

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 30
Professor, Dept. of CSE, AU
Advantages of user-defined function
• The program will be easier to understand,
maintain and debug.

• Reusable codes that can be used in other


programs

• A large program can be divided into smaller


modules. Hence, a large project can be divided
among many programmers.
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 31
Professor, Dept. of CSE, AU
3 steps of using functions in C
• Function declaration or prototype – This informs
compiler about the function name, function parameters
and return value’s data type.

• Function call – This calls the actual function

• Function definition – This contains all the statements


to be executed.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 32
Professor, Dept. of CSE, AU
Example
#include<stdio.h>
void square ( );
void main( )
{
printf ( "\n Program to find Square");
square ( ) ;
}
void square ( )
{
int n, sq ;
printf ( "\n Enter a Number\n");
scanf ( "%d", &n ) ;
sq=n*n;
printf(“square is =%d”,sq);
}
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 33
Professor, Dept. of CSE, AU
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 34
Professor, Dept. of CSE, AU
Function prototype
• A function prototype is the declaration of a function that specifies
– function's name

– Parameters (arguments)

– return type.

• A function prototype gives information to the compiler.

Example: return_type function_name( parameter list );


int sum(int num1, int num2);

int square(int n);

float area(int r);

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 35
Professor, Dept. of CSE, AU
Function Arguments
• If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parametersof the function.

• Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.

• While calling a function, there are two ways in which arguments can be passed to a
function −
Sr.No. Call Type & Description
1 Call by valueThis method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside the
function have no effect on the argument.

2 Call by referenceThis method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the
argument.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 36
Professor, Dept. of CSE, AU
Array
• Array is homogeneous collection of elements
stored at contiguous location.

E.g. int a[5];

int b[10][20];

float marks[10];

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 37
Professor, Dept. of CSE, AU
Passing Array to Function
• Way-1
– Formal parameters as a pointer −
void myFunction(int *param)
{...}
• Way-2
– Formal parameters as a sized array −
void myFunction(int param[10])
{...}
• Way-3
– Formal parameters as an unsized array −
void myFunction(int param[])
{...}

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 38
Professor, Dept. of CSE, AU
Example
#include <stdio.h> void Average(int arr[], int size)
void Average(int arr[], int size); {
void main ( ) int i;
{ float avg;
int n[5] = {1000, 2, 3, 17, 50};
float sum = 0;
Average( n, 5) ;
for (i = 0; i < size; i++)
}
{
sum= sum+ arr[i];
}
avg = sum / size;
printf( "Average value is: %f ", avg );
}

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 39
Professor, Dept. of CSE, AU
Recursion
• The process in which a function calls itself
directly or indirectly is called recursion.

• Types of recursion:
– 1. Direct

– 2. Indirect

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 40
Professor, Dept. of CSE, AU
Direct Recursion
A function is said to be direct recursive if it calls itself
directly.
void recursion()
{
recursion();
/* function calls itself */
}
int main()
{
recursion();
}
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 41
Professor, Dept. of CSE, AU
Indirect Recursion
A function is said to be indirect recursive if it calls another function and this new
function calls the first calling function again.

Example:
int func1(int n)
{
if (n<=1)
return 1;
else
return func2(n);
}
int func2(int n)
{ return func1(n);
}
• In this program, func1() calls func2(), which is a new function. But this new
function func2() calls the first calling function, func1(), again. This makes the above
function an indirect recursive function.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 42
Professor, Dept. of CSE, AU
Advantages and Disadvantages of Recursion
• Advantages:

– Recursion makes program elegant and cleaner.

– Better understanding of algorithm.

– Less code and small programs.

• Disadvantages:

– Slow speed.

– More memory space is required to store intermediate results.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 43
Professor, Dept. of CSE, AU
Sum of Natural Numbers Using Recursion
#include <stdio.h>
int addNumbers(int n);
void main()
{ int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d", addNumbers(num));
}
int addNumbers(int n)
{ if(n != 0)
return n + addNumbers(n-1);
else
return n;
}
Output
Enter a positive integer: 20
Sum = 210

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 44
Professor, Dept. of CSE, AU
Factorial program in C using recursion
• As factorial is n!= (n-1)! * n,
• factorial function calculates the factorial by
recursively multiplying n with factorial of (n-1).

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 45
Professor, Dept. of CSE, AU
Factorial program in C using recursion
#include<stdio.h> int factorial(int n)
int factorial(int); {
void main() if (n == 0)
{ return 1;
int n; else
int f; return(n * factorial(n-1));
printf("Enter an integer to find its factorial\n"); }
scanf("%d", &n);
if (n < 0) Explanation:
printf("Factorial of negative integers isn't •The number whose factorial is to be found is stored
defined.\n"); in the variable n.
else •A recursive function factorial(n) calculates the
{ factorial of the number.
f = factorial(n); •As factorial is n!= (n-1)! * n,
•factorial function calculates the factorial by
printf(“\nFactorial = %d", f); recursively multiplying n with factorial of (n-1).
} •Finally, when n = 0, it returns 1 because 0! = 1.
}

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 46
Professor, Dept. of CSE, AU
Program for Fibonacci Series
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{ return 0;
}
if(i == 1)
{ return 1; }
return fibonacci(i-1) + fibonacci(i-2); }
void main()
{ int i;
for (i = 0; i < 10; i++)
{ printf("%d\t\n", fibonacci(i));
}
}
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 47
Professor, Dept. of CSE, AU
Ackermann function
• In computability theory, the Ackermann function, named after Wilhelm Ackermann, is
one of the earliest-discovered examples of a total computable function that is
not primitive recursive. All primitive recursive functions are total and computable, but the
Ackermann function illustrates that not all total computable functions are primitive
recursive.

• One common version, the two-argument Ackermann–Péter function, is defined as


follows for nonnegative integers m and n:

• Its value grows rapidly, even for small inputs. For example, A(4, 2) is an integer of
19,729 decimal digits.

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 48
Professor, Dept. of CSE, AU
C Program to implement Ackermann
function using recursion

#include<stdio.h> int A(int m, int n)


int A(int m, int n); {
main() if(m==0)
return n+1;
{ else if(n==0)
int m,n; return A(m-1,1);
printf("Enter two numbers :: \n"); else
scanf("%d%d",&m,&n); return A(m-1,A(m,n-1));
printf("\nOUTPUT :: %d\n",A(m,n)); }
}

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 49
Professor, Dept. of CSE, AU
Summary
A function is a mini-program or a subprogram.
Functions are used to modularize the program.
Library and user-defined are two types of functions.
A function consists of a declaration, function body, and a function call part.
Function declaration and body are mandatory.
A function call can be optional in a program.
C program has at least one function; it is the main function ().
Each function has a name, data type of return value or a void, parameters.
Each function must be defined and declared in your C program.
Keep in mind that ordinary variables in a C function are destroyed as soon as we exit the function call.
The arguments passed to a function will not be changed because they passed by value none by address.
The variable scope is referred to as the visibility of variables within a program
There are global and local variables in C programming

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 50
Professor, Dept. of CSE, AU
References
1. https://www.tutorialspoint.com/cprogramming/c_recursion.htm

2. https://www.geeksforgeeks.org/recursion/

3. https://beginnersbook.com/2014/01/c-passing-array-to-function-
example/

4. https://www.tutorialspoint.com/cprogramming/c_passing_arrays_
to_functions.htm

5. Let Us C , Yashwant Kanetkar

6. Programming in C, 2011, by J.B. Dixit

7. Basics of C Programming, 2011, by J.B. Dixit


Compiled by Er. K. Ravikanth, Assistant
1/27/2025 51
Professor, Dept. of CSE, AU
QUERIES

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 52
Professor, Dept. of CSE, AU
Compiled by Er. K. Ravikanth, Assistant
1/27/2025 53
Professor, Dept. of CSE, AU
ALL THE BEST - DEAR STUDENTS
HOPE FOR GOOD ACADEMIC RESULTS

Compiled by Er. K. Ravikanth, Assistant


1/27/2025 54
Professor, Dept. of CSE, AU

You might also like