Vous êtes sur la page 1sur 20

LESSON 4

Function

Learning Objectives:
At the end of the chapter, the students are expected to:

Know the advantages of using Function; and

Differentiate the call by value and call by reference.

1. FUNCTION IN C
The

heart

decomposition.

of

effective

Taking

problem

problem

and

solving

breaking

is

it

problem

into

small,

manageable pieces is critical to writing large programs. In C,


the

function

construct

is

used

to

implement

this

top-down

method of programming.
A

function

is

section

of

program

which

performs

specific task. The task assigned to a function is performed


whenever C encounters the function name. A function is actually a
subprogram that is, a function performs a task within a program
and is written in a form similar to C main program.

1.1 The advantages using FUNCTION


1. Using function fits naturally with a top-down design approach.
Use of function helps to streamline the design of a program and
prevents small details from obscuring the program logic.
2. Functions can often be used than once in a program and in
several different programs, thereby sharing programming time. A
function can be viewed as a blank box which performs a particular
task within a program. It accepts input and produces certain
output. When programming with function, you are plugging various
block boxes into your program to accomplish various necessary
tasks. Certain common task appears regularly in totally unrelated
programs.

In

such

cases,

the

same

function

can

be

used

repeatedly.
3.

Using

function

provides

natural

method

for

dividing

programming task among a team of programmers. By defining a


function as a block box which accepts certain inputs and produces

certain output, the function can be programmed as an independent


entity.
4. Function can be tested individually. By testing functions at a
time, the process of debugging an entire program is organized and
simplified.

1.2 FUNCTION DECLARATIONS


The function declaration has a name of a function, the type
of the value to be returned (if there are any) and the number and
types of the arguments that must be supplied in a call of the
function. A function declaration may contain argument names.

syntax:
type function_name (parameter list)

Example
int ccmit (int bsit, int bscs);
void ccmit ();
float ccmit (float x, float y);

1.3 FUNCTION DEFINITION


The code that describes what a function does is called a
function definition. It must not be confused with the function
declaration.

The

function

definition

must

general form:
type function_name (parameter list)

have

the

following

declaraction

local variables

statement;
}
Everything before the first brace comprises the header of
the

function

definition,

and

everything

between

the

braces

comprises the body of the function definition. The parameter-list


is a comma-separated list of declaration.
A function definition starts with the type of the function.
If no value is returned, then the type is void. If the type is
something other than void, then the value is returned by the
function will be converted, if necessary, to this type. The name
of the function is followed by a parenthesized list of parameter
declarations. The parameter act as a placeholders for values that
are passed when the function is invoked. Sometimes, to emphasize
their

role

as

placeholders,

these

parameters

are

called

the

formal parameters of the function. The function body is a block,


or compound statement, and it too may contain declarations.

Example
double twice(double x)
{
return(2.0*x)
}

/*function definition*/

int all_add(int a, int b)


{ int c;
:
return(a+b+c);}
1.3 LOCAL VARIABLES TO A FUNCTION

/*function definition*/

Any variables declared in the body of function are said to


be local to that function. Other variables ay be declared
external to the function. These are called global variables.

Variables that are declared inside the function are called


local variables. In C, they are referred to as AUTOMATIC
VARIABLES or the keyword auto.

Local variables can be reference only by statements that are


inside the block in which the variables are declared.

Local variables are not known outside their own code.


should

remember

that

block

of

code

is

begun

when

You
an

opening curly brace is encountered and terminated when a


closing curly brace is found.

One of the most important things to remember about local


variable is that they EXIST only while the block code in
which they are declared is executing That is, local variable
is created upon entry into its block and destroyed upon
exit.

The most common code block in which local variables are


declared is in function.

Sample Program
#include<stdio.h>
#include<conio.h>
int a=33
main()
{

int b = 77;
/*b is local variable to main()*/
printf(a = %d\n,a); /*a is global variable to main()*/
printf(b=%d\n,b);
return 0;
getch();
}

1.3.2 GLOBAL VARIABLE TO A FUNCTION

Known throughout the entire program and maybe used by any


piece of code. Also, they hold their values during the
entire execution of the program.

Global variables are created by declaring them outside of


any

function.

They

maybe

accessed

by

any

expression

regardless of what function that expression is in.

Storage for global variables is in fixed region of memory


set aside for this purpose by the compiler.

Global variables are very helpful when the same amount of


data is used in many functions in your program.

You

should

avoid

using

unnecessary

global

variables,

however, three(3) reasons:


1. They

take-up

memory

the

entire

time

your

program

is

executing not just when they are needed.


2. Using global variables when local variable will do makes
a function less general because it relies on something
that must be defined outside by itself.

3. Using a large number of global variables can lead to


program

error

because

of

unknown

and

unwanted,

side

effects.
1.2.3 THE return STATEMENT

The return statement may or may not include an expression.


Syntax:
return;

The

return(expression);

expression

being

returned

can

be

enclosed

in

parenthesis, but this is not required. When a return statement is


encountered, execution of the function is terminated and control
is

passed

statement

back

to

contains

the
an

calling

environment.

expression,

then

the

If

the

value

return
of

the

expression is passed back to the calling environment as well.


Moreover, this value will be converted, if necessary to the type
of the function as specified in the function definition.

Example
float f(char a, char b, char c)
{
int i;
:
:
return i;
/*the value returned will be converted to a
float*/
}

There can be zero or more return statements in a function. If


there is no return statement, then control variable is passed
back to the calling environment when the closing brace of the
body is encountered. This is called falling off the end.
Program segment
double absolute_value( double x)
{
if(x >= 0.0)
return x;
else
return x;
}

1.4 FUNCTION PROTOTYPES

Functions should be declared before they are used. ANSI C


provides for a new function declaration syntax called the
functional prototype.

A function prototype tells the compiler the number and the


type of arguments that are to be passed to the function and
the

type

of

the

value

that

is

to

be

returned

by

the

function.
Example
double sqrt(double);

this tells the compiler that sqrt() is a function that takes a


single argument of type double and returns a double.

Syntax:
type function_name(parameter type list);

The parameter type list is typically a comma-separated list


of types. Identifiers are optional.

Example of function prototype:


void funct1(char c, int i); is equivalent

to void funct1(char,

int);

Function prototype allows the compiler to check the code


more thoroughly.

Also, values passed to function are properly coerced.

Note: Function Prototype in C++


In C++, function prototypes are required and the use of void in
the parameter type list in both function prototypes and the
function definition is optional.

Example
void funct1()

is equivalent to void funct1(void)

1.5 GIVING NAMES TO PARAMETER/PARAMETER LISTS


A function header identifies the parameters which are to be
passed to the function. In the header and in the actual body of
the function, the parameters used are FORMAL parameters which are
replaced by the ACTUAL parameter when the function is called.
Since the FORMAL parameters are eventually replaced, they are not

program

variable.

In

particular,

you

can

assign

to

FORMAL

parameters the names of program variable which will eventually


replace them.
2. FUNCTION INVOCATION AND CALL BY VALUE
A program is made up of one or more function definitions,
with one of these being main(). Program execution always begin
with main(). When program control encounters a function name, the
function is called, or invoked. This means that the program
control passes to that function. After the function does its
work, program control is passed back to the calling environment,
which then continues with its work.
Functions
appropriate

are

list

of

invoked

by

arguments

writing
within

their

names

parenthesis.

and

an

Typically,

these arguments match in number and type(or compatible type) the


parameters in the parameter list in the function definition. The
compiler enforces type compatibility when function prototypes are
used. All arguments are passed call by value. This means that
each argument is evaluated and its value is used locally in
place of the corresponding formal parameter.
A function call comes from either the main program or within
a function. The function originating a function call is referred
to as the calling function or calling environment.

HOW VALUE PARAMETER/CALL BY VALUE WORKS


A value parameter is a copy of a variable which is private
to the function. The function is given a copy of the actual
parameter

to

manipulate.

However,

the

manipulation

affect any of the variables in the calling program.

does

not

Sample Program:
#include<stdio.h>
#include<conio.h>
int sum;
/*global declaration*/
void funct_sample ( int y);
void main()
{
int n =5; clrscr();
print(The value of n here is %d,n);
funct_sample(n);
printf(\nValue of n is %d,n);
getch();
}
funct_sample( int y)
{
/* Sample function using call by value */
y*= 3;
printf(The new value of y is %d, y);
OUTPUT:
The value of n here is 5
The new value of y is 15
Value of n here is 5
Even though n is passed to funct_sample() and received by formal
parameter y, the value n which y in the body of that function is
changed,

the

value

of

in

the

calling

environment

remains

unchanged. It is the value of n that is being passed, not n


itself.

3. CALL BY REFERENCE OR VARIABLE PARAMETERS

To change the value of variable in the calling environment,


other languages provide the call by reference mechanism.

The use of addresses of variables as argument to function


can produce the effect of

call by reference

For the function to effect call by reference, pointers


must

be

used

in

the

parameter

list

in

the

function

definition. When the function is called, address of the


variables must be passed as argument.

In passing a variable parameter to a function, C does not


pass the actual value. Instead, it passes a pointer to a
variable being passed, that is, we pass the address of the
memory location holding the value of the variable being
passed.

& is used as address operator means the address of

* is called as indirection operator means the content of


address

Illustration
Address of the parameter value of parameter
16825

*50126
address of parameter is
being passed to the function

Sample program
#include<stdio.h>
#include<conio.h>
compute_rating(float midterm, float final, float *rating)
{
/* Function that will compute the final rating */
*rating = (midterm + final)/2;

}
main()
{
char name[25];
float mid,fin,fin_grd;
clrscr();
putsf(Please enter you name);
gets(name);
printf(Enter your midterm grade);
scanf(%f,&mid);
printf(\nEnter you final grade);
scanf(%f,&fin);
compute_rating(mid,fin, &fin_grd);
printf(%s got a final rating of %f, name,fin_grd);
getch();
return 0;
}

EXERCISE NO. 4
NAME:_________________________________ DATE: ____________
YR. & SEC. ___________________________ SCORE:____________
A.
1. What is a function? What is the syntax of a function?

___________________________________________________________
2. What is the use of the data type void?
___________________________________________________________
3. Explain a function that is called by value?
___________________________________________________________
4. What is an address? A pointer? Explain a function that is
called by reference?
___________________________________________________________
___________________________________________________________
___________________________________________________________
5. Explain a function that returns a value?
___________________________________________________________
___________________________________________________________
___________________________________________________________
B. TRACING
1. Trace the following programs:
(a)
void trace1(int x, int y)
{
X = 5; *y =2;
printf(%2d %2d\n, x, *y);
}
main( )
{
int x, y;
clrscr( );
x = y = 3;
trace1(x, &y);
printf(%2d %2d\n, x, y);
getch( );

return 0;
}
(b)
void trace(int x, int *y, int z)
{
x = 1; *y=2;z=4;
printf("%2d %2d %2d\n",x, *y, z);
}
main()
{
int x=1, y=3,z=4;
clrscr();
printf("%2d %2d %2d\n",x,y,z);
trace(y,&x,z);
printf("%2d %2d %2d\n",x,y,z);
trace(x,&z,y);
printf("%2d %2d %2d\n",x,y,z);
trace(z,&y,x);
printf("%2d %2d %2d\n",x,y,z);
getch();
return 0;
}
(c)
#include<stdio.h>
#include<conio.h>
void kar1(char *c, char b, char *a)
{
*a = 'c'; b = 'a'; *c = 'b';
printf("%c %c %c\n", *a, b, *c);
}
void kar2(char *b, char *a, char *c)
{
*a = 'b'; *b='c'; *c ='a';
printf("%c %c %c\n", *a, *b, *c);
}
main()
{
char a = 'a', b = 'b', c = 'c';
clrscr();
printf("%c %c %c\n", a, b, c);
kar1(&a,b,&c);
printf("%c %c %c\n", a, b, c);
kar2(&a,&b,&c);

printf("%c %c %c\n", a, b, c);


kar1(&c,b,&a);
printf("%c %c %c\n", a, b, c);
kar2(&c,&a,&b);
printf("%c %c %c\n", a, b, c);
getch();
return 0;
}
(d)
#include<stdio.h>
#include<conio.h>
void kar1(char *a, char *b, char *c)
{
*a = 'c'; *b='a'; *c ='b';
printf("%c %c %c\n", *a, *b, *c);
}
main()
{
char a = 'c', b = 'b', c = 'a';
clrscr();
printf("%c %c %c\n", a, b, c);
kar1(&a,&b,&c);
printf("%c %c %c\n", a, b, c);
kar1(&c,&b,&a);
printf("%c %c %c\n", a, b, c);
kar1(&b,&a,&c);
printf("%c %c %c\n", a, b, c);
getch();
return 0;
}

C. PROGRAMMING. Write a program for the following problem.


PROGRAMMING EXERCISES 4-1
N factorial can be define as the product of all integer from 1 to
N and it is denoted by the symbol N!.0! (zero factorial) is

defined a 1.

Write a program that will input N and would call

the function factorial that will return N factorial. (Determine


first if N is a nonnegative integer).
PROGRAMMING EXERCISES 4-2
An integer is considered prime if its only factors are 1 and
itself.

1 can be considered a prime integer because its factors

are 1 and only 1.

Write a program that will input a nonnegative

and would call the function prime that returns 0 for true and 1
for

false.

(Precondition:

Test

if

the

entered

value

is

nonnegative)
PROGRAMMING EXERCISES 4-3
Write a function int is_prime(int n) that returns 1 if n is prime
and 0 otherwise.
Hint: if k and n are positive integer, then k divides n if and
only if n % k has value 0.
PROGRAMMING EXERCISES 4-4
A famous conjecture, called the GOLDBACH conjecture, says that
every even integer n greater than 2 has the property tat it is
the

sum

of

two

prime

numbers.

extensively to test this conjecture.

Computers

have

been

used

No counter example has been

found. Write a program the will prove that the conjecture is true
for all the even integers between the symbolic constants START
and FINISH.

For example, if you write:

#define START 700


#define FINISH 1100
Then the output of your program might look like this:

Every even number greater than 2 is the sum of two primes:


700 = 17
702 = 11
704 = 3
:
:
1098 = 5
1100 = 3

+ 683
+ 691
+ 701
+ 1093
+ 1097

PROGRAMMING EXERCISES 4-5


Four track stars have entered the mile race at the Penn Relays.
Write a program that scans in the race time in minutes and
seconds for a runner and computes and displays the speed in feet
per seconds and in meters per seconds.
Hint: there are 5280 feet in one mile, and one kilometer equals
3282 feet.
Write and call a function that displays instructions to the
program users.
PROGRAMMING EXERCISES 4-6
Two positive integers i and j are considered to be relatively
prime if there exist no integer greater than 1 that divides them
both. Write a function rel_prime that has two input parameters, I
and j, and returns a value of 1 if and only if I and j are
relatively prime.
0.
CASE STUDY 1

Otherwise, rel_prime should return a value of

The proper divisor of an integer N are the positive divisors less


than N, a positive integer is said to be DEFICIENT, PERFECT or
ABUNDANT numbers if the sum of its proper divisors is less than,
equal to or greater than the number respectively. Write a program
using function call by reference to input integer N and call
function KOMPUTE to determine of integer N is DEFICIENT, PERFECT
or ABUNDANT .
Example:
Input N : 8
Proper divisors are 1,2 4
Sum of proper divisors: 1 + 2 + 4 = 7
7 < 8

is DEFICIENT

Input N : 6
Proper divisors are 1,2 3
Sum of proper divisors: 1 + 2 + 3 = 6
6 < 6

is PERFECT

Input N : 12
Proper divisors are 1,2, 3, 4,6
Sum of proper divisors: 1 + 2 + 3 + 4 + 6 = 16
16 > 12

is ABUNDANT

CASE STUDY 2
Write a program to call function TRIANGLE to determine if a given
sides

is

equilateral,

EQUILATERAL

if

all

isosceles

the

three

or

sides

scalene.
have

the

triangle
same

is

length.

ISOSCELES if only two sides have the same length and SCALENE if

no sides have the same length.

Input the length of the three

sides and print whether the triangle is equilateral, isosceles or


scalene.
CASE STUDY 3

Military Time

General Program Definition


In military, when one gives a time it is usually in a 24hour notation (e.g. 1300 means 1:00PM). Write a program that
converts

from

24-hour

notation

to

12-hour

notation

using

function.
Input Specifications
The input must be a single integer ranging from 0 to 2400.
Any other value must result into an input error which the program
should display as a message to the user before it halts program
execution.
Output Specifications
Output the time in 12-hour notation using the following
format: 1:00 PM using a colon to separate the hour part from the
minute part and adding the abbreviations AM or PM to indicate
what part of the day it is. Note that you must observe the 2digit display.

Vous aimerez peut-être aussi