Functions
1
Function
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
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 instructions
3
Function Control Flow
void print_banner () int main ()
{ {
print_banner {
printf(“************\n”);
} print_banner ();
}
print_banner {
void main () print_banner ();
{ }
...
print_banner (); }
...
print_banner ();
} 4
Calling function (caller) may pass
information to the called function (callee)
as parameters/arguments
For example, the numbers to add
The callee may return a single value to
the caller
Some functions may not return anything
5
Calling function (Caller)
Called function (Callee) parameter
void main() float cent2fahr(float data)
{ float cent, fahr; {
scanf(“%f”,¢); float result;
fahr = cent2fahr(cent); result = data*9/5 + 32;
printf(“%fC = %fF\n”, return result;
cent, fahr); }
}
Parameter passed
Returning value
Calling/Invoking the cent2fahr function
6
How it runs
Output
float cent2fahr(float data)
$ ./a.out
{
float result; 32
printf(“data = %f\n”, data); Input is 32.000000
result = data*9/5 + 32; data = 32.000000
return result; 32.000000C = 89.599998F
printf(“result = %f\n”, result);
} $./a.out
void main() -45.6
{ float cent, fahr; Input is -45.599998
scanf(“%f”,¢); data = -45.599998
printf(“Input is %f\n”, cent);
-45.599998C = -50.079998F
fahr = cent2fahr(cent);
$
printf(“%fC = %fF\n”, cent, fahr);
}
7
Another Example void main()
{
int factorial (int m) int n;
for (n=1; n<=10; n++)
{
printf (“%d! = %d \n”,
int i, temp=1;
n, factorial (n) );
for (i=1; i<=m; i++) }
temp = temp * i;
return (temp);
} Output
1! = 1
2! = 2
3! = 6 …….. upto 10!
8
Why Functions?
Allows one to develop a program in a
modular fashion
Divide-and-conquer approach
Construct
a program from small pieces or
components
Use existing functions as building blocks for
new programs
Abstraction: hide internal details (library
functions)
9
Defining a Function
A function definition has two parts:
The first line, called header
The body of the function
return-value-type function-name ( parameter-list )
{
declarations and statements
}
10
The first line contains the return-value-type,
the function name, and optionally a set of
comma-separated arguments enclosed in
parentheses
Each argument has an associated type
declaration
The arguments are called formal
arguments or formal parameters
The body of the function is actually a block of
statement that defines the action to be taken
by the function
11
Return-value type Formal parameters
int gcd (int A, int B)
{
int temp;
while ((B % A) != 0) {
temp = B % A;
BODY
B = A;
A = temp;
} Value returned
return (A);
} 12
Return value
A function can return a value
Using return statement
Like all values in C, a function return value has a type
The return value can be assigned to a variable in the
caller
int x, y, z;
scanf(“%d%d”, &x, &y);
z = gcd(x,y);
printf(“GCD of %d and %d is %d\n”, x, y, z);
13
Function Not Returning Any Value
Example: A function which prints if a number is
divisible by 7 or not
void div7 (int n)
{ Return type is void
if ((n % 7) == 0)
printf (“%d is divisible by 7”, n);
else
printf (“%d is not divisible by 7”, n);
return; Optional
} 14
return statement
In a value-returning function (result type is not void), return
does two distinct things
specify the value returned by the execution of the
function
terminate that execution of the callee and transfer control
back to the caller
A function can only return one value
The value can be any expression matching the return
type
but it might contain more than one return statement.
In a void function
return is optional at the end of the function body.
return may also be used to terminate execution of the
function explicitly.
No return value should appear following return. 15
void compute_and_print_itax ()
{
float income;
scanf (“%f”, &income); Terminate function
if (income < 50000) { execution before
printf (“Income tax = Nil\n”); reaching the end
return;
}
if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000));
return;
}
if (income < 150000) {
printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);
return ;
}
printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);
}
16
Calling a function
Called by specifying the function name and parameters
in an instruction in the calling function
When a function is called from some other function, the
corresponding arguments in the function call are called
actual arguments or actual parameters
The function call must include a matching actual
parameter for each formal parameter
Position of an actual parameters in the parameter list
in the call must match the position of the
corresponding formal parameter in the function
definition
The formal and actual arguments must match in their
data types
17
Example
Formal parameters
double operate (double x, double y, char op)
{
void main () switch (op) {
{ case ‘+’ : return x+y+0.5 ;
double x, y, z; case ‘~’ : if (x>y)
char op; return x-y + 0.5;
... return y-x+0.5;
z = operate (x, y, op); case ‘x’ : return x*y + 0.5;
... default : return –1;
} }
}
Actual parameters 18
When the function is executed, the value
of the actual parameter is copied to the
formal parameter
parameter passing
void main ()
{ ... double area (double r)
double circum; {
... return (3.14*r*r);
area1 = area(circum/2.0);
}
...
}
19
Another Example
/* Compute the GCD of four numbers */
void main()
{
int n1, n2, n3, n4, result;
scanf (“%d %d %d %d”, &n1, &n2, &n3, &n4);
result = gcd ( gcd (n1, n2), gcd (n3, n4) );
printf (“The GCD of %d, %d, %d and %d is %d \n”,
n1, n2, n3, n4, result);
}
func-gcd.c 20
Another Example
void main()
int prime(int x)
{
{
int numb, flag, j=3;
int i, test;
scanf(“%d”,&numb);
i=2, test =0;
while (j <=numb)
while ((i <= sqrt(x)) && (test
{
==0))
flag = prime(j);
{ if (x%i==0) test = 1;
if (flag==0)
i++;
printf(“%d is prime\n”,j);
}
j++;
return test;
}
}
}
21
Tracking the flow of control
void main()
{ int prime(int x)
int numb, flag, j=3; {
scanf(“%d”,&numb); int i, test;
printf(“numb = %d \n”,numb); i = 2; test = 0;
while (j <= numb) printf(“In function, x = %d \n”,x);
{ printf(“Main, j = %d\n”,j); while ((i <= sqrt(x)) && (test == 0))
flag = prime(j); { if (x%i == 0) test = 1;
printf(“Main, flag = %d\n”,flag);
i++;
if (flag == 0)
}
printf(“%d is prime\n”,j);
printf(“Returning, test = %d \n”,test);
j++;
} return test;
} }
22
The output
5
numb = 5 Returning, test = 1
Main, j = 3
Main, flag = 1
In function, x = 3
Main, j = 5
Returning, test = 0
Main, flag = 0 In function, x = 5
3 is prime Returning, test = 0
Main, j = 4 Main, flag = 0
In function, x = 4 5 is prime
23
Points to note
The identifiers used as formal parameters are
“local”.
Notrecognized outside the function
Names of formal and actual arguments may differ
A value-returning function is called by including
it in an expression
A function with return type T (≠ void) can be used
anywhere an expression of type T can be used
24
Returning control back to the caller
If nothing returned
return;
or,
until reaches the last right brace ending
the function body
If something returned
return expression;
25
Function Prototypes
Usually, a function is defined before it is called
main() is the last function in the program written
Easy for the compiler to identify function definitions
in a single scan through the file
However, many programmers prefer a top-down
approach, where the functions are written after main()
Must be some way to tell the compiler
Function prototypes are used for this purpose
Only needed if function definition comes after
use
26
Function prototypes are usually written at the
beginning of a program, ahead of any functions
(including main())
Prototypes can specify parameter names or just
types (more common)
Examples:
int gcd (int , int );
void div7 (int number);
Note the semicolon at the end of the line.
The parameter name, if specifed, can be
anything; but it is a good practice to use the
same names as in the function definition
27
Some more points
A function cannot be defined within another
function
All function definitions must be disjoint
Nested function calls are allowed
A calls B, B calls C, C calls D, etc.
The function called last will be the first to
return
A function can also call itself, either directly or
in a cycle
A calls B, B calls C, C calls back A.
Called recursive call or recursion
28
Example: main calls ncr, ncr calls fact
int ncr (int n, int r)
int ncr (int n, int r); {
int fact (int n); return (fact(n) / fact(r) /
fact(n-r));
void main() }
{
int i, m, n, sum=0; int fact (int n)
scanf (“%d %d”, &m, &n); {
for (i=1; i<=m; i+=2) int i, temp=1;
sum = sum + ncr (n, i); for (i=1; i<=n; i++)
printf (“Result: %d \n”, temp *= i;
sum); return (temp);
} }
29
Local variables
A function can define its own local variables
The locals have meaning only within the function
Each execution of the function uses a new set of
locals
Local variables cease to exist when the function
returns
Parameters are also local
30
Local variables
/* Find the area of a circle with diameter d */
double circle_area (double d)
{ parameter
double radius, area; local
radius = d/2.0; variables
area = 3.14*radius*radius;
return (area);
}
31
Revisiting nCr void main()
{
int fact(int x) int n, r;
{ int i,fact=1; scanf(“%d%d”,&n,&r);
for(i=2; i<=x; ++i) fact=fact*i; printf(“n=%d, r=%d,
return fact; nCr=%d\n”,n, r, ncr(n,r));
} }
int ncr(int x,int y) The variable x in function fact and
{ x in function ncr are different.
int p,q,r;
p=fact(x); The values computed from the
q=fact (y); arguments at the point of call are
r = fact(x-y); copied on to the corresponding
return p/(q*r); parameters of the called function
} before it starts execution.
32
Scope of a variable
Part of the program from which the value of the variable
can be used (seen)
Scope of a variable - Within the block in which the variable
is defined
Block = group of statements enclosed within { }
Local variable – scope is usually the function in which it is
defined
So two local variables of two functions can have the
same name, but they are different variables
Global variables – declared outside all functions (even
main)
scope is entire program by default, but can be hidden in
a block if local variable of same name defined
33
#include <stdio.h>
int A = 1; Variable
void main() Global variable
Scope
{
myProc();
printf ( "A = %d\n", A);
} Hides the global A
void myProc() Output:
{ int A = 2;
if ( A==2 ) A= 3
{ A= 2
int A = 3;
printf ( "A = %d\n", A); A= 1
}
printf ( "A = %d\n", A);
}
34
Parameter Passing: by Value
and by Reference
Used when invoking functions
Call by value
Passes the value of the argument to the function
Execution of the function does not change the
actual parameters
All changes to a parameter done inside the function are
done on a copy of the actual parameter
The copy is removed when the function returns to the
caller
The value of the actual parameter in the caller is not
affected
Avoids accidental changes
35
Call by reference
Passes the address to the original argument.
Execution of the function may affect the original
Not directly supported in C except for arrays
36
Parameter passing & return: 1
void main()
{
int a=10, b;
printf (“Initially a = %d\n”, a); Output
b = change (a);
printf (“a = %d, b = %d\n”, a, b); Initially a = 10
} Before x = 10
int change (int x)
{ After x = 5
printf (“Before x = %d\n”,x); a = 10, b = 5
x = x / 2;
printf (“After x = %d\n”, x);
return (x);
}
37
Parameter passing & return: 2
void main()
{
int x=10, b;
printf (“M: Initially x = %d\n”, x); Output
b = change (x); M: Initially x = 10
printf (“M: x = %d, b = %d\n”, x, b);
}
F: Before x = 10
int change (int x) F: After x = 5
{
M: x = 10, b = 5
printf (“F: Before x = %d\n”,x);
x = x / 2;
printf (“F: After x = %d\n”, x);
return (x);
}
38
Parameter passing & return: 3
void main()
{
int x=10, b;
printf (“M: Initially x = %d\n”, x);
x = change (x); Output
printf (“M: x = %d, b = %d\n”, x, x);
M: Initially x = 10
}
int change (int x) F: Before x = 10
{ F: After x = 5
printf (“F: Before x = %d\n”,x);
x = x / 2; M: x = 5, b = 5
printf (“F: After x = %d\n”, x);
return (x);
}
39
Parameter passing & return: 4
void main()
Output
{
int x=10, y=5; M1: x = 10, y = 5
printf (“M1: x = %d, y = %d\n”, x, y);
F1: x = 10, y = 5
interchange (x, y);
printf (“M2: x = %d, y = %d\n”, x, y); F2: x = 5, y = 10
}
M2: x = 10, y = 5
void interchange (int x, int y)
{ int temp;
printf (“F1: x = %d, y = %d\n”, x, y); How do we write an
temp= x; x = y; y = temp; interchange function?
printf (“F2: x = %d, y = %d\n”, x, y);
}
(will see later)
40
Passing Arrays to Function
Array element can be passed to functions
as ordinary arguments
IsFactor (x[i], x[0])
sin (x[5])
41
Passing Entire Array to a
Function
An array name can be used as an argument to a
function
Permits the entire array to be passed to the function
The way it is passed differs from that for ordinary
variables
Rules:
The array name must appear by itself as argument,
without brackets or subscripts
The corresponding formal argument is written in the
same manner
Declared by writing the array name with a pair of
empty brackets
42
Whole Array as Parameters
const int ASIZE = 5;
float average (int B[ ]) Only Array Name/address passed.
{ [ ] mentioned to indicate that
int i, total=0; is an array.
for (i=0; i<ASIZE; i++)
total = total + B[i];
return ((float) total / (float) ASIZE);
}
void main ( ) {
int x[ASIZE] ; float x_avg;
x = {10, 20, 30, 40, 50};
x_avg = average (x) ;
Called only with actual array name
} 43
Contd. void main()
{
int n;
We don’t need to
float list[100], avg;
write the array size.
:
It works with arrays
avg = average (n, list);
of any size.
:
}
float average (int a, float x[])
{
:
sum = sum + x[i];
}
44
Arrays used as Output Parameters
void VectorSum (int a[ ], int b[ ], int vsum[ ], int length) {
int i;
for (i=0; i<length; i=i+1)
vsum[i] = a[i] + b[i] ;
}
void PrintVector (int a[ ], int length) {
int i;
for (i=0; i<length; i++) printf (“%d “, a[i]);
}
void main () {
int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3];
VectorSum (x, y, z, 3) ;
PrintVector (z, 3) ;
}
vector-sum.c
45
The Actual Mechanism
When an array is passed to a function, the values
of the array elements are not passed to the
function
The array name is interpreted as the address of
the first array element
The formal argument therefore becomes a
pointer to the first array element
When an array element is accessed inside the
function, the address is calculated using the
formula stated before
Changes made inside the function are thus also
reflected in the calling program
46
Contd.
Passing parameters in this way is called
call-by-reference
Normally parameters are passed in C using
call-by-value
Basically what it means?
If a function changes the values of array elements,
then these changes will be made to the original
array that is passed to the function
This does not apply when an individual element is
passed on as argument
47
Passing 2-d Arrays as Parameters
Similar to that for 1-D arrays
The array contents are not copied into the function
Rather, the address of the first element is passed
For calculating the address of an element in a 2-d
array, we need:
The starting address of the array in memory
Number of bytes per element
Number of columns in the array
The above three pieces of information must be known
to the function
48
Example Usage
void add (int x[][25], int
y[][25], int rows, int cols)
int main() {
{ :
int a[15][25], b[15]25]; }
:
:
add (a, b, 15, 25);
:
} We can also write
int x[15][25], y[15][25];
But at least 2nd dimension
must be given
49
Library Functions
50
Library Functions
Set of functions already written for you,
and bundled in a “library”
Example: printf, scanf, getchar,
C library provides a large number of
functions for many things
We look at functions for mathematical use
51
Math Library Functions
Math library functions
perform common mathematical calculations
Must include a special header file
#include <math.h>
Example
printf ("%f", sqrt(900.0));
Calls function sqrt, which returns the square
root of its argument
Return values of math functions can be
float/double/long double
Arguments may be constants, variables, or
expressions
52
Math Library Functions
double acos(double x) – Compute arc cosine of x.
double asin(double x) – Compute arc sine of x.
double atan(double x) – Compute arc tangent of x.
double atan2(double y, double x) – Compute arc tangent of y/x.
double cos(double x) – Compute cosine of angle in radians.
double cosh(double x) – Compute the hyperbolic cosine of x.
double sin(double x) – Compute sine of angle in radians.
double sinh(double x) – Compute the hyperbolic sine of x.
double tan(double x) – Compute tangent of angle in radians.
double tanh(double x) – Compute the hyperbolic tangent of x.
53
Math Library Functions
double ceil(double x) – Get smallest integral value that exceeds x.
double floor(double x) – Get largest integral value less than x.
double exp(double x) – Compute exponential of x.
double fabs (double x) – Compute absolute value of x.
double log(double x) – Compute log to the base e of x.
double log10 (double x) – Compute log to the base 10 of x.
double pow (double x, double y) – Compute x raised to the power y.
double sqrt(double x) – Compute the square root of x.
54