Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Functions in C
Modular Design
Modularity in C
Why Functions?
Reusability
The Structure of a C
Function
Function header
Function Body
{
// Body of the function
}
Structure of Function: An
Example
int max (int a, int b, int c)
function header
{
int max_value;
max_value = a;
if ( b > max_value)
max_value = b;
if ( c > max_value)
max_value = c;
return (max_value);
}
function body
Types of functions
yourself
Library functions
Function Calls
Worker
worker1
worker4
worker2
worker5
worker3
Function_name(arg1, arg2,,argN)
Here Function_name is the name of the function and
arg1, arg2, argN is the data value (or actual
parameter) that will be passed to the function.The
arguments in the function call need to correspond to p
arameters in the function definition.
z);
/* call function */
float square(float x)
{
return (x * x);
}
main()
{
int x, y, z, largest;
largest = max3 ( x, y, z);
Main (Caller)
Function
}
int max(int a, int b, int c)
Calling Function
{
int max;
...
}
Function Prototypes
So that the C compiler can correctly
interpret function calls it is necessary to dec
lare each C function before it is used in a pr
ogram.
The C language provides a statement for
declaring function called a function prototyp
e.
A function prototype informs the compiler
about the type of value returned by the
function and the type and number of argum
ents that the function expects.
For example, the function prototype for the
function max3() is
int
void a(void)
{
printf(A Starts\n);
b();
c();
printf(A Ends\n);
}
void main()
{
a();
}
void b(void)
{
printf(B
c();
printf(B
}
void c(void)
{
printf(C
printf(C
}
Starts\n);
Ends\n);
Starts\n);
Ends\n);
Call by Value
Call by Value
Local Variables
Example of Local
Variable
#include <stdio.h>
void function1 (void);
main()
{
int i = 1; /* Local to main */
function1();
...
}
void function1(void)
{
int i = 10;
/* Local to function1 */
...
}
Global Variables
Example of Global
Variable
int random(void)
int reseed(void)
int seed;
main()
{
...
}
int new_seed;
int random(void)
{
}
int reseed( void)
{
/* global
variable */
/* global
variable */
Recursion
Example
int rec(int x);
void main(){
int a, fact; printf(Enter a number);
scanf(%d,&a);
printf(Factorial Value %d,rec(a));
int rec(int x){
if(x==1) return (1);
else
int f=x*rec(x-1);
return f;
}
void main(){
int a; printf(Enter a number);
scanf(%d,&a);
printf(Factorial Value %d,rec(a));