11_Function in C
11_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
printf( ) main ( )
scanf() written by the programmer
strlen()
getchar()
--- C allows user to include
--- multiple user defined
functions
Need for User defined functions
Category 1 NO NO
Category 2 YES NO
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
• A function call is an expression that passes control and arguments (if any) to a
function.
z
Arguments passed but no return value
Flow of Arguments between Function Blocks - Example
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()
{ {
A5
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
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
1
1
Static Variable Example