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

Unit 4-Functions in C

The document provides an overview of functions in C programming, explaining their purpose, types, and syntax. It covers key concepts such as function declaration, calling, and definitions, along with the differences between call by value and call by reference. Additionally, it discusses recursion, advantages and disadvantages of using functions, and how to pass arrays to functions.

Uploaded by

ayushamahajan
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)
11 views

Unit 4-Functions in C

The document provides an overview of functions in C programming, explaining their purpose, types, and syntax. It covers key concepts such as function declaration, calling, and definitions, along with the differences between call by value and call by reference. Additionally, it discusses recursion, advantages and disadvantages of using functions, and how to pass arrays to functions.

Uploaded by

ayushamahajan
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
You are on page 1/ 60

Functions in C

1
Function
 Function is a program segment that carries out some specific,well-
defined task.


Example
A function to add two numbers
A function to find the largest of n numbers
 A function will carry out its intended task whenever it is called or
invoked
Can be called multiple times

2
Function

Every C program consists of one or more functions

One of these functions must be called main

Execution of the program always begins by carrying out the


instructions in main

Functions call other functions as instructi ons

3
Why Functions?

 Function make a program more readable. Breaking the code into smaller
functions keep program structured understandable and reusable.

 Functions help in code modularity, which means that the entire code is
divided into separate blocks, each self-contained and performing a
different task

4
Why Functions?

#include<stdio.h>
int main()
{
printf(“hello”);
printf(“hello”);
printf(“hello”);
return 0;
}

5
Why Functions?
#include<stdio.h>

int main()
{
for(i=1;i<=100)
{
print();
}
return 0;
}
void print()
{
printf(“hello”);
}
6
Types of Functions

7
Standard Library Function
 Library function in c are inbuilt function which are grouped together and placed in
common place called library. Each library function in c perform specific operation.
 These functions are defined in header file.

e.g. printf() function is a standard library function to send formatted output to screen.

8
User Defined Function
 C allow programmer to define functions.Such functions created by user are called
user-defined functions.
 Depending upon the complexity and requirment of program ,you can create as
many user -defined functions as you want.

Syntax of Functions in C

The syntax of function can be divided into 3 aspects:

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

9
C functions aspects syntax

Return_typefunction_name(arguments list)
Function definition {
Body of function;
}

Function call
Function_name(arguments list);

Function declaration Return_type function_name(argument list);

Function Declaration
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names

10
int factorial (int m); Function declaration (prototype)

int main() int factorial (int m)


{ {
int n; int i, temp=1;
for (n=1; n<=10; n++) for (i=1; i<=m; i++)
printf (“%d! = %d \n”, temp = temp * i;
n, factorial (n) ); return (temp);
} }

Function call

Output Function definition

1! = 1
2! = 2
3! = 6 …….. upto 10!
11
12
Formal Arguments and Actual Arguments:

Formal arguments − Formal parameters are also called function parameters or function
arguments. They are used in the function definition to accept the values from the caller of the
function.

Syntax of Formal Parameters in C


return_type function_name(parameter1_type parameter1_name, parameter2_type, ... )
{
// function body
}

Example of Formal Parameters in C

int add(int a, int b)


{
return a + b;
}

13
Actual Arguments:

Actual arguments − Actual parameters are the values that are passed to the function during a
function call. They are also known as arguments. Actual parameters are used to provide the
values to the formal parameters of the function. Actual parameters can be of any data type
such as int, float, char, etc.

Syntax of Actual Parameters in C

function_name(actual_parameter1, actual_parameter2, ...);

Example of Formal Parameters in C

int main()
{
int sum= add(10, 20);
return 0;
}
14
#include<stdio.h>

int add(int a, int b)


{
int sum = a + b; Formal Parameter
return sum;
}
int main()
{
int sum = add(10, 20);
printf("%d",sum);
return 0;
} Actual Parameter

15
Types of C Functions Based On Arguments & Return Value

Functions in C can be of four types depending upon the arguments passed and value returns.

1 Functions that take arguments and return value.


2 Functions that take arguments and return no value.
3 Functions that take no arguments and return value.
4 Functions that neither take arguments nor return value.

16
Function In C With Arguments & Return Value
#include <stdio.h>
int sub(int,int); //function with return value and arguments
void main()
{
int x=10,y=7;
int res = sub(x,y);
printf("x-y = %d",res);
}

int sub(int a,int b) //function with return value and arguments


{
return(a-b); // return value
}

17
Functions with arguments and without return values

#include <stdio.h>
int main()
{
void sum(float,float); //function with arguments and no return value
float x=10.56,y=7.22;
sum(x,y);
}

void sum(float a,float b) //function with arguments and no return value


{
float z = a+b;
printf("x + y = %f",z);
}

18
Functions without arguments and with return values

#include<stdio.h>
int main()
{
int sum();
int c = sum();
printf("Sum = %d",c);
}
int sum() //function with no arguments and return data type
{
int x=10,y=20,z=5;
printf("x = %d ; y = %d ; z = %d \n",x,y,z);
int sum = x+y+z;
return(sum);
}

19
Functions without arguments and without return values

#include<stdio.h>
int main()
{
void sum();
sum();
}

void sum() //function with no arguments and return data type


{
int x=15,y=35,z=5;
printf("x = %d ; y = %d ; z = %d \n",x,y,z);
int sum = x+y+z;
printf("Sum = %d",sum);
}

20
Concept of Call by Value & Call by reference

21
Call by Value
#include<stdio.h>
void change(int num)
{
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
22
How Does "Call by Value" Work in C?
When the function is executed, the value of the actual parameter is copied to the
formal parameter

23
Call by Reference
When a function is called by reference, the address of the actual argument
variables passed, instead of their values

int swap(int *x, int *y)


{
int z;
z = *x; // save the value at address x
*x = *y; //put y into x
*y = z; //put z into y
return 0;
}

24
#include <stdio.h>
int swap(int *x, int *y)
{
int z;
z = *x; // save the value at address x
*x = *y; // put y into x
*y = z; // put z into y */
return 0;
}
int main()
{
int a = 10;
int b = 20;
printf("Before swap, value of a: %d\n", a );
printf("Before swap, value of b: %d\n", b );
// calling a function to swap the values
swap(&a, &b);
printf("After swap, value of a: %d\n", a);
printf("After swap, value of b: %d\n", b);
return 0;
} 25
Call by Reference

26
Difference between call by value and call reference
Call by value Call reference
The function is invoked by passing the The function is invoked by passing the
parameter’s value in Call by Value, which is parameter’s reference (i.e., the location of
why it has this name. variables) in Call by Reference, which is why
it has this name.
In Call by Value, any changes made to the In Call by Reference, changes to the function’s
function’s argument do not affect the passed argument are reflected in the passed parameter
parameter as the value of the parameter is as both refer to the same location.
copied.
Call by Value passes a copy of the variable . Call by Reference passes the variable itself
In Call by Value, the actual arguments and In Call by Reference, the actual arguments and
passed parameters of a function refer to passed parameters of a function refer to the
different memory locations. same memory location.
In Call by Value, the original value is not In Call by Reference, the original value is
modified. modified.
In Call by Value, the values of the variables are In Call by Reference, the address of the
passed using a simple technique. variables is stored using pointer variables.
27
Advantages & Disadvantages Functions

Advantages:

1 Reduces Repetition: Functions help avoid repeating the same code in a


program, making it more efficient and easier to maintain.

2 Enhances Readability: They improve code readability by breaking it into


smaller, modular pieces, making it easier to understand.

3 Re-usability: Functions can be called multiple times from different parts of


the program, promoting code reuse.

4 Reduces Program Size: By organizing code into functions, it reduces the


overall size of the program and keeps it manageable.

28
Advantages & Disadvantages Functions

Disadvantages

1 Cannot Return Multiple Values: C functions can return only a single value.
If you need to return multiple values.

2 Limited Access to Variables: Functions have limited access to variables


defined outside their scope. This can make it difficult to share data between
functions, especially when dealing with large amounts of data or complex
data structures

3 Complexity: Using functions can sometimes introduce additional


complexity, especially when dealing with function parameters, return values.

29
Pass Arrays to Functions
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[])
{
float sum = 0.0;
for (int i = 0; i < 6; ++i)
{
sum += num[i];
}
return sum; 30
Pass Multidimensional Arrays to a Function
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);

return 0;
}
31
void displayNumbers(int num[2][2])
{
printf("Displaying:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
printf("%d\n", num[i][j]);
}
}
}

32
Call by Reference

• When data is passed by reference means, actually passing a pointer to the


original data's memory location.

• This means any changes made within the function will directly affect the
original data outside the function.

• This is achieved by passing pointers as function arguments, making it call by


reference.

• Using pointers as function arguments allows you to achieve call by reference


behavior.

• Useful when you want to modify the original data inside a function and have
those changes reflected outside the function.

33
Example:

#include <stdio.h>

void modifyValue(int *ptr) {


*ptr = *ptr * 2;
}

int main() {
int num = 5;
printf("Original value: %d\n", num);
modifyValue(&num);
printf("Modified value: %d\n", num);
return 0;
}
Output:
Original value: 5
Modified value: 10
34
Recursion in C
• Recursion is the process of a function calling itself repeatedly till the given
condition is satisfied.

• A function that calls itself directly or indirectly is called a recursive function and
such kind of function calls are called recursive calls.

The key components of a recursive solution are:

Base case(s): These are the simplest cases that can be solved directly without further
recursion. They help terminate the recursive calls.

Recursive case(s): These are the cases where the function calls itself with a modified
version of the problem, bringing it closer to the base case(s).

35
The basic syntax structure of the recursive functions is:

type function_name (args)


{ // function statements

// base condition

// recursion case (recursive call)


}

36
Factorial (N!)

• N! = (N-1)! * N [for N > 1]


• 1! = 1
• 3!
= 2! * 3
= (1! * 2) * 3
=1*2*3
• Recursive design:
–Decomposition: (N-1)!
–Composition: * N
–Base case: 1!

37
Factorial Method

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition)
fact = factorial(n – 1) * n; // composition
else // base case
fact = 1;
return fact;
}

38
int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition)
fact = factorial(n – 1) * n; // composition
else // base case
fact = 1;
return fact;
}

39
public static int factorial(int 3)
{
int fact;
if (n > 1)
fact = factorial(2) * 3;
else
fact = 1;
return fact;
}

int factorial(int 2)
{
int fact;
if (n > 1)
fact = factorial(1) * 2;
else
fact = 1;
return fact;
}

40
{ public static int factorial(int 3)
{ int fact;
int(n
if fact;
> 1)
iffact
(n > =1)factorial(2) * 3;
fact = factorial(2) * 3;
else
else
fact
fact == 1;
1;
return fact;
return fact;
}}

int factorial(int 2)
{
int fact;
if (n > 1)
fact = factorial(1) * 2;
else
fact = 1;
return fact;
}

int factorial(int 2)
{
int fact;
if (n > 1)
fact = factorial(1) * 2;
else
fact = 1;
return fact; 41
int factorial(int 3)
{
int fact;
if (n > 1)
fact = factorial(2) * 3;
else
fact = 1;
return fact;
}

int factorial(int 2)
{
int fact;
if (n > 1)
fact = factorial(1) * 2;
else
fact = 1;
return fact;
}
int factorial(int 1)
{
int fact;
if (n > 1)
fact = factorial(n - 1) * n;
else
fact = 1;
return 1;
42
int factorial(int 3)
{
int fact;
if (n > 1)
fact = factorial(2) * 3;
else
fact = 1;
return fact;
}

int factorial(int 2)
{
int fact;
if (n > 1)
fact = 1 * 2;
else
fact = 1;
return fact;
}

int factorial(int 1)
{
int fact;
if (n > 1)
fact = factorial(n - 1) * n;
else
fact = 1;
return 1; 43
int factorial(int 3)
{
int fact;
if (n > 1)
fact = factorial(2) * 3;
else
fact = 1;
return fact;
}

int factorial(int 2)
{
int fact;
if (n > 1)
fact = 1 * 2;
else
fact = 1;
return 2;
}

44
int factorial(int 3)
{
int fact;
if (n > 1)
fact = 2 * 3;
else
fact = 1;
return 6;
}

45
Execution Trace (decomposition)

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition) factorial(4)
fact = factorial(n – 1) * n; (composition)
else // base case *
fact = 1;
return fact; factorial(3) 4
}

46
Execution Trace (decomposition)

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition) factorial(4)
fact = factorial(n – 1) * n; (composition)
else // base case *
fact = 1;
return fact; factorial(3) 4
}
*
factorial(2) 3

47
Execution Trace (decomposition)

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition) factorial(4)
fact = factorial(n – 1) * n; (composition)
else // base case *
fact = 1;
return fact; factorial(3) 4
}
*
factorial(2) 3
*

factorial(1) 2

48
Execution Trace (decomposition)

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition) factorial(4)
fact = factorial(n – 1) * n; (composition)
else // base case *
fact = 1;
return fact; factorial(3) 4
}
*
factorial(2) 3
*

factorial(1)->1 2

49
Execution Trace (decomposition)

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition) factorial(4)
fact = factorial(n – 1) * n; (composition)
else // base case *
fact = 1;
return fact; factorial(3) 4
}
*
factorial(2)->2 3

50
Execution Trace (decomposition)

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition) factorial(4)
fact = factorial(n – 1) * n; (composition)
else // base case *
fact = 1;
return fact; factorial(3)->6 4
}

51
Execution Trace (decomposition)

int factorial(int n)
{
int fact;
if (n > 1) // recursive case (decomposition)
fact = factorial(n – 1) * n; (composition)
else // base case *
fact = 1;
return fact;
}

factorial(4)->24

52
Improved factorial Methodc

int factorial(int n)
{
int fact=1; // base case value

if (n > 1) // recursive case (decomposition)


fact = factorial(n – 1) * n; // composition
// else do nothing; base case

return fact;
}

53
Fibonacci Numbers

• The Nth Fibonacci number is the sum of the previous two


Fibonacci numbers
• 0, 1, 1, 2, 3, 5, 8, 13, …
• Recursive Design:
– Decomposition & Composition
• fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
– Base case:
• fibonacci(1) = 0
• fibonacci(2) = 1

54
Fibonacci Method

int fibonacci(int n)
{
int fib;
if (n > 2)
fib = fibonacci(n-1) + fibonacci(n-2);
else if (n == 2)
fib = 1;
else
fib = 0;
return fib;
}

55
Execution Trace (decomposition)

fibonacci(4)

fibonacci(3) fibonacci(2)

56
Execution Trace (decomposition)

fibonacci(4)

fibonacci(3) fibonacci(2)

fibonacci(2)->1 fibonacci(1)->0

57
Execution Trace (decomposition)

fibonacci(4)

fibonacci(3)->1 fibonacci(2)->1

58
Execution Trace (composition)

fibonacci(4)->2

59
THANK YOU
60

Vishwakarma Institute of Technology, Pune

You might also like