0% found this document useful (0 votes)
29 views26 pages

11_Function in C

Uploaded by

ayusssssh100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views26 pages

11_Function in C

Uploaded by

ayusssssh100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Function in C

What is Function in C?
• A set of statements grouped together into a single logical unit is referred to
as Function.
• A function is a self-contained block of code that performs a particular task.
• Example
main()
{
int a,b,c;
c=a+b;
}
• Note: main() is a specially recognized function in C and every C program
must have exactly one main().
Categories of C Functions

Library User Defined


Functions Functions

printf( ) main ( )
scanf() written by the programmer
strlen()
getchar()
--- C allows user to include
--- multiple user defined
functions
Need for User defined functions

• Enables Modularization of large


complex problems.
• Facilitates top down modular main()
programming.
• Ease of debugging & testing.
• Ease in modifying program. Fun-1 Fun-2 Fun-n
• Repeated use of modules.
• Reduce length of program.
How does Multiple Functions Work
Fun ()
main() Arguments
(if any) {
{
---
st-1 Called function
---
St-2
Return values }
St-3: Invoke Fun() (if any)
St-4
St-5
}
Points to Remember
Multiple user defined functions allowed.
Calling function
Any function can invoke any other function and any number of
times
A function can also invoke itself – such are called Recursive
function
A function may send parameters to other function called as
ARGUEMENTS.
A function may perform computation and RETURN back results.
Interaction between Function Blocks – Categories
based on Arguments & Return Values
• Based on the exchange of arguments and return values between
interacting functions, there may be FOUR categories

CATEGORY Arguments: Data flowing Return: Data being returned


from Calling Function to by Called Function to Calling
Called Function Function

Category 1 NO NO

Category 2 YES NO

Category 3 YES YES

Category 4 NO YES
The C Function - Format
• User defined functions must • General Format (function
be given names – The rules definition):
for naming identifier also
holds good for naming
function.
data_type fun_name (argument list)
{
• General Convention of
function declaration is to local variable declaration;
declare a prototype before
main() and at the end of executable statements;
main the function to }
defined.
Example – Display messages from various blocks

void disp(); // function prototype void disp() //function definition


main() {
{ printf(“I am at fun Disp”);
printf(“hello from main”); }
disp(); // invocation Output
printf(“bye from main”); hello from main
} I am at fun Disp
bye from main

Category – 1 (No argument / No Return)


Flow of Arguments between Function Blocks
• It is possible to capture data in one function block and transfer them to other
function blocks whichever are invoked. This phenomenon is called Function Call.

• A function call is an expression that passes control and arguments (if any) to a
function.

• The arguments passed may be absolute value or address.

• Whenever a function is called and arguments passed as values, such invocation is


called as CALL-BY-VALUES.

• Whenever a function is called and arguments passed as addresses, such invocation is


called as CALL-BY-REFERENCE.
Flow of Arguments between Function Blocks - Example
Formal Parameter
void sum(int, int); void sum(int x, int y)
main() {
int z;
{
Actual z=x+y;
int a,b; Parameter
printf(“The Sum =%d”, z);
a=5, b=6; } Output
sum(a,b); The Sum = 11
Bye from main
a=5
printf(“bye from main”); c
b=6 o
} x p
CALL BY VALUE y y

z
Arguments passed but no return value
Flow of Arguments between Function Blocks - Example

sum(int, int); sum(int x, int y)


main() {
{ return (x+y);
int a,b, result;
a=5, b=6; }
result = sum(a,b);
a=5
printf(“The sum is%d”, result); Output c
The Sum = 11 b=6 o
} x p
y y
Arguments passed and value returned back
result
CALL BY VALUE
Handling Non-Integer Function

float compute(int, int); float compute(int x, int y)


main() {
{
return ((float) (x/y));
int a,b;
}
float result;
Output
a=25, b=7; The result is = 3.5714
result = compute(a,b);
printf(“The result is%f”, result); Default return type of any function is int

} In order to obtain non-integer value,


function must be declared with the data
type
Function invocation using Call-by-Reference

int compute (int *, int *); int compute (int *p1, int *p2)
{
#include <stdio.h> return (* p1 + * p2);
int main() }
{
int a=5,b=6, z; Output
Result is 11
z=compute(&a, &b);
printf(“Result is%d", z);
Pointers p1 & p2 are
return 0; pointing to a and b
} respectively
How Call by Value & Call by Reference differ?
mod(int); mod(int *);

main() main()
{ {
A5
int a=5; int a=5;
mod(a); mod(&a);
X <-- 5
printf(“a is %d”, a); +100=105 printf(“a is %d”, a);
} } A  5+100
mod(int x) 105
{ mod(int *x)
x=x+100; {
printf(“x is %d”, x); *x= *x+100;
} }
*x  &a
Call by Reference
Call by Value
Function invocation using Call-by-Value & Call-by-Reference

float compute(float, float *); float compute(float r1, float *p)


main() {
{ float a;
float r, area, perimeter; a=(float) 3.14*r1*r1;
radius = 4; *p=(float) 2*3.14*r1;
area = compute(r, &perimeter); return a;
printf(“Area=%f, area); }
printf(“Perimeter=%f”, perimeter);
}
Accessing Array using Pointer & Function

void modify(int *); void modify(int *p)


{
#include <stdio.h> int j;
for(j=0;j<5;j++)
void main() {
{ *p = *p+100;
int a[5]={10,20,30,40,50}, i; p++;
modify(a); }
Output
for(i=0;i<5;i++) } 110
printf("%d\n", a[i]); 120
130
} 140
150
Passing Array to a Function

Size not declared

#include <stdio.h> void disp(int b[])


void disp(); {
int main() int i;
{ for(i=0;i<3;i++)
int a[3]={10,20,30}; printf("%d\n", b[i]);
OUTPUT
disp(a); }
10
return 0; 20
30
}
Recursive Function
• A function invoking itself directly or
indirectly is called Recursive Function.

• A recursive function usually forms a


Fun 1
cycle of invokation and therefore
suitable terminal conditions must be Direct Recursion – Self Invocation
placed to break the infinite cycle of
invocation.
• Eg: Fun 1 Fun 2 Fun N
myfun()
{
---
myfun(); Indirect Recursion – Invocation through other function
---
}
Recursive Function – When to use
• Whenever a problem can be
redefined in terms of problems
in terms of smaller units which
are corelated.
• The problem thus can be
reduced entirely to simple cases
by calling the recursive function.
• If this is a simple case Recursive splitting of the problem into
solve it a problem of size 1 and another
else problem of size n-1.
redefine the problem using
recursion
Recursive Function – Example
Ch: 5th scan . terminal
// Print Character Backwards void prn()
Ch: 4th scan T Pending to print
{
void prn(); Ch: 3rd scan I Pending to print
char ch;
Ch: 2nd scan M Pending to print
main() scanf(“%c”, &ch); Pending to print
Ch: 1st scan S
{ if( ch!= ‘.’)
printf (“Enter characters and { When terminal achieved, next
type ‘.’ to terminate”); prn(); statement start executing – print
statement: POP operation starts.
prn();
printf(“%c”, ch);
printf(“bye from main”); }
T I M S
} }
Test Case
Input: SMIT. Printed in reverse order
Output: TIMS
Recursive Function – Example contd..

ch ch != ‘.’ Action Pending

T Y prn(); Print T T I M S

I Y prn(); Print I
M Y prn(); Print M Printed in reverse order

S Y prn(); Print S
. N Pop operation
Recursive Function – Example contd..Factorial of
a function using recursion
#include<stdio.h> long int multiplyNumbers(int n) {
long int multiplyNumbers(int n); if (n>=1)
int main() { return n*multiplyNumbers(n-1);
int n; else
printf("Enter a positive integer: "); return 1;
scanf("%d",&n); }
printf("Factorial of %d = %ld", n,
multiplyNumbers(n));
return 0;}
Static Variable Demonstration in Function

• Recall Static Variables are local Variables which retain its


values even after the control jumps out of the function block.

• On the contrary, an Auto variable does not retain its value.

• Static Variables are used whenever the value of a variable


declared within a function block is required to be retained
irrespective of closure of the function.
Auto Variable Example

#include<stdio.h> int fun()


int fun(); {
int main() int count = 0;
{ count++;
printf("\n%d ", fun()); return count;
printf("\n%d ", fun()); }
return 0;
} Output

1
1
Static Variable Example

#include<stdio.h> int fun()


int fun(); {
int main() static int count = 0;
{ count++;
printf("\n%d ", fun()); return count;
printf("\n%d ", fun()); }
printf("\n%d ", fun());
Output
return 0;
1
}
2
3
Practice Program
• Add an element in the array at the top position
• Delete an element from the array at the top position
• Add an element at the bottom position
• Delete an element from the top position
• Add / Delete an element in ith position – Adjust the elements in the
array.
[0] 102
[0] 102 [0] 102
[1] 76 Del element at pos
[1] 87 [1] 76
[2] 45 [2] value is 76
[2] 45 [2] 87 Add element at pos
[3] 506
[3] 506 [3] 45 [1] value is 76
[4] 0
[4] 506

You might also like