Co101-Lecture Notes Part 2
Co101-Lecture Notes Part 2
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
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
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
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
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
} 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
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
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
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.
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
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));
} }
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.
:
}
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