You are on page 1of 29

Faculty of Computer Science and Information Technology

BIC 10204 Algorithm and Programming

CHAPTER 6
Functions

Outline
• Modular Programming
• User defined functions
• Function elements:
– Function definition
– Function prototype
– Function call
• Types of functions

1
Objectives
• After this lesson, you should be able to:
Explain function concept
Write C program using function concept.

Similarities between variables and


function
• Variables • Functions
– Variables’ names are – Functions’ names are
considered to be considered to be
identifiers (follow identifiers (follow
naming identifiers naming identifiers
rules) rules)
– Has types (int, float, – Has types (int, float,
double, char, etc.) double, char, etc.)
associated to them associated to them
– Must be declared prior – Must be declared prior
to their use to their use
4

2
Functions

Library functions Programmer-defined


functions

Math IO Others Does not Receive Receive


receive and but does and return
not return not return value
value any value

Let’s try this…

Write a program that can


add, subtract, multiply
and divide two numbers.

3
#include<stdio.h>

void main(){
int num1,num2;
int addition, substraction, multiplication, division;

printf("\n Enter two numbers");


scanf("%d%d",&num1,&num2);

addition=num1+num2;
substraction=num2-num1;
multiplication=num1*num2;
division=num1/num2;

printf("\n Result of addittion\t\t %d + %d = %d",num1,num2,addition);


printf("\n Result of substraction\t\t %d - %d = %d",num2,num1,substraction);
printf("\n Result of multiplication\t\t %d * %d = %d",num1,num2,multiplication);
printf("\n Result of division\t\t %d / %d = %d",num1,num2,division);
}

What do you think?


• There are so many operations in
main().
• We can separate the operations (addition,
subtraction, multiplication and division )
into several functions.
• So, how to divide them ?

4
Separate the functions
#include<stdio.h> //get two numbers
printf("\n Enter two numbers");
scanf("%d%d",&num1,&num2);
void main()
{ //Addition and its output
int num1,num2; addition=num1+num2;
int addition, substraction, multiplication, division; printf("\n Result of addittion\t\t "
"%d + %d = %d",num1,num2,addition);
printf("\n Enter two numbers");
scanf("%d%d",&num1,&num2); //Substraction and its output
substraction=num2-num1;
addition=num1+num2; printf("\n Result of substraction\t\t"
substraction=num2-num1; "%d - %d = %d",num2,num1,substraction);
multiplication=num1*num2;
division=num1/num2;
//multiplication and its output
printf("\n Result of addittion\t\t " multiplication=num1*num2;
printf("\n Result of multiplication\t\t"
"%d + %d = %d",num1,num2,addition); "%d * %d = %d",num1,num2,multiplication);
printf("\n Result of substraction\t\t"
"%d - %d = %d",num2,num1,substraction);
printf("\n Result of multiplication\t\t" //division and its output
"%d * %d = %d",num1,num2,multiplication); division=num1/num2;
printf("\n Result of division\t\t"
printf("\n Result of division\t\t" "%d / %d = %d",num1,num2,division);
"%d / %d = %d",num1,num2,division);
}

Separate the operations into functions


#include<stdio.h> void substraction(int c,int d)
{
void addition(int r,int s); int substract;
substract=d-c;
void substraction(int c,int d);
printf("\nResult of substraction\t"
void multiplication(int e,int f); "%d - %d = %d",d,c,substract);
void division(int m,int n); }

void main(){ void multiplication(int e,int f)


int num1,num2; {
int multiply;
printf("\n Enter two numbers");
multiply=e*f;
scanf("%d%d",&num1,&num2); printf("\nResult of multiplication\t"
addition(num1,num2); "%d * %d = %d",e,f,multiply);
substraction(num1,num2); }
multiplication(num1,num2);
division(num1,num2); void division(int m,int n){
int divide;
}
divide=m/n;
printf("\nResult of division \t"
void addition(int r,int s) "%d / %d = %d",m,n,divide);
{ }
int add;
add=r+s;
printf("\nResult of addition\t"
"%d + %d = %d",r,s,add);
}

10

5
Modular Programming
• Modular programming in C is called Functions
• This technique is called divide and conquer
• Problem is divided into smaller pieces or
modules
• Module can be divided into sub-modules
• Benefits:
– program structure is readable
– make program development more manageable
– software reusability – using existing functions as
building block to create new program

11

Function Is a program segment that performs specific


tasks, made up of C statements

Has TWO types: User-defined functions


Created by user for
Standard library functions specific purposes
-Example:
exit(), scanf(), printf(),
clrscr ()

Function prototype
Functions Function definition
elements
Function call
12

6
Separate the operations into functions
#include<stdio.h> void substraction(int c,int d)
{
void addition(int r,int s); int substract;
void substraction(int c,int d); Function substract=d-c;
void multiplication(int e,int f); prototype printf("\nResult of substraction\t"
void division(int m,int n); "%d - %d = %d",d,c,substract);
}
void main(){
int num1,num2; void multiplication(int e,int f)
printf("\n Enter two numbers"); {
scanf("%d%d",&num1,&num2); int multiply;
addition(num1,num2); multiply=e*f;
substraction(num1,num2); Function printf("\nResult of multiplication\t"
multiplication(num1,num2); call "%d * %d = %d",e,f,multiply);
division(num1,num2); }
}
void division(int m,int n){
void addition(int r,int s) int divide;
{ divide=m/n;
int add; Function printf("\nResult of division \t"
add=r+s; definition "%d / %d = %d",m,n,divide);
printf("\nResult of addition\t" }
"%d + %d = %d",r,s,add);
}

13

Function Prototype
• The function prototype
– Must be added to a C program before the main()
function, if call that function before defining it.
– It tells the compiler:
1.what type of value the function returns (function return type)
2.number and types of parameters
3.order in which these parameters are expected.
– There is no need for a prototype if the function is
called after its definition.

14

7
Function Prototype (2)
Function prototype example
void addition (int a, int b);
or
void addition (int, int);

where;

what type of value the function void


returns (function return type)

number and types of two (2) parameters (a and b)


parameters int and int

order in which these int a followed by int b


parameters are expected.
15

#include<stdio.h>
void multiplication(int e,int f)
void
void
addition(int ,int );
substraction(int c,int d);
Function {
int multiply;
void multiplication(int,int); Prototype multiply=e*f;
void division(int m,int n); printf("\nResult of multiplication\t"
"%d * %d = %d",e,f,multiply);
void main(){ }
int num1,num2;
printf("\n Enter two numbers"); void division(int m,int n){
scanf("%d%d",&num1,&num2); int divide;
addition(num1,num2); divide=m/n;
substraction(num1,num2); printf("\nResult of division \t"
multiplication(num1,num2); "%d / %d = %d",m,n,divide);
division(num1,num2); }
}

void addition(int r,int s)


{
int add;
add=r+s;
printf("\nResult of addition\t"
"%d + %d = %d",r,s,add);
}

void substraction(int c,int d)


{
int substract;
substract=d-c;
printf("\nResult of substraction\t"
"%d - %d = %d",d,c,substract);
}

16

8
Function Definition
• A function definition has two principal
components:
– the first line (including the parameter/ argument
declarations), and
– the body of the function.
• The first line of a function definition contains
– type of the value returned by the function (function
return type)
– the function name, and
– (optionally) a set of parameters/ arguments,
separated by commas and enclosed in parentheses.

17

Function Definition (2)

First line

Body

18

9
#include<stdio.h>

void addition(int ,int );


void substraction(int c,int d);

void main(){
int num1,num2;
Parameters / arguments
printf("\n Enter two numbers");
Function data type
scanf("%d%d",&num1,&num2);
return type
addition(num1,num2);
r and s are parameters
substraction(num1,num2);
Function name / arguments
}

void addition(int r,int s)


{ Function
int add; definition
add=r+s;
printf("\nResult of addition\t%d + %d = %d",r,s,add);
}

void substraction(int c,int d)


{
int substract;
substract=d-c;
printf("\nResult of substraction\t%d - %d = %d",d,c,substract);
} 19

Function Definition (3)


• Format of a function definition
return-value-type function-name (parameter-list)
{
declarations
A return value of type void
statements indicates a function
} does not return a value.

20

10
Function Definition (4)
• Function Definition: argument/parameter
– The arguments are called formal argument
• because they represent the names of data items that are
transferred into the function from the calling portion of the
program.
– There are also known as parameters or formal
parameters.
– The identifiers used as formal arguments are “local”
• because they are not recognized outside of the function.
• the names need not to be same as the names of the actual
arguments in the calling portion of the program.

21

Function Definition (5)


Arguments / Parameters

r and s are arguments /


parameters

22

11
Function Definition (6)
• Function Definition: compound
statement/body
– compound statement / function body
defines the action to be taken by the function.
– can contain expression statements, other
compound statements, control statements,
and so on.
– It should include one or more return
statements, in order to return a value to the
calling portion of the program.
23

Example
Function prototype & definition
#include <stdio.h>

int mod(int, int); /* Function Prototype */

void main()
{
printf("The mod is: %d ", mod(4,5));
}

int mod(int a, int b) /* Function Definition */

{
return a % b; OUTPUT?
}
24

12
Example
• Function with definition but without prototype

#include <stdio.h>

int sum(int a, int b) /* Function Definition */


{
return a+b;
}

void main()
{
printf("The sum is: %d ", sum(4,5));
}
OUTPUT?

25

Function Calls
• A function can be accessed (i.e., called) by
– specifying function name, followed by a list of arguments
enclosed in parentheses and separated by commas.
• If the function call does not require any arguments
– empty pair of parentheses must follow the name of the function.
• The arguments appearing in the function call are referred
to as actual arguments, in contrast to the formal
arguments that appear in the first line of the function
definition.

26

13
#include<stdio.h>

void addition(int ,int );


void substraction(int c,int d);

void main(){
int num1,num2;
printf("\n Enter two numbers");
scanf("%d%d",&num1,&num2); num1 and num2 are
addition(num1,num2);
Function calls actual parameters /
substraction(num1,num2); arguments in function
} call
void addition(int r,int s)
{
int add; Function definition
add=r+s;
printf("\nResult of addition\t”
“%d + %d = %d",r,s,add);
}
void substraction(int c,int d) r, s, c and d are
{
formal parameters /
arguments in
int substract; function definition
substract=d-c;
printf("\nResult of substraction\t”
“%d - %d = %d",d,c,substract);
} 27

Function Calls (2)


• In a normal function call
– there will be one actual argument for each formal argument.
– may be expressed as constants, single variables, or more
complex expressions.
• If the function returns a value, the function access is
written in a statement; e.g.,
b = sum(a);
• If the function does not return anything, the function
access appears by itself; e.g.,
view(a,b,c);

28

14
Function Calls (3)
• A function can be called by
– the main function
– other functions
– itself (recursion)
• In C, functions call can be
1.by value
2.by reference

29

Function Calls (4)


1. Call by value
– Copy of variable passed to function
– If that variable is modified within the function, only the
copy has been modified, the actual variable is not
modified
2. Call by reference
– Pass the address of a variable (i.e. a pointer) to a
function
– The variable pointed to can be modified within that
function

30

15
Function Calls (5)
• Example Call By Value

finval = FuncByValue(finval);

finval is /*The FuncByValue function*/


type float float FuncByValue(float fval)
to receive
the result
{
of return fval*fval;
fval*fval }

31

Function Calls (cont.)


• Example Call By Reference

FuncByReference(&finref)

• Use & to pass the address of a variable to the function

• Value of the referenced variable passed to the function is


modified after returning from the function.

the function
access
void FuncByReference(float *fvalptr)
appears by {
itself since it *fvalptr = *fvalptr * *fvalptr;
does not }
return a
32
value

16
Scope of variable
•Scope determine where the variable will be used.
•Two types of scope: GLOBAL and LOCAL

It’s scope begins at the


point of its declarations
GLOBAL variable and terminates at the
end of file.
Example
#include <stdio.h>
int a,b;
Declared before main() float c;
void main()
a, b and c are {
global variable } 33

Scope of variable (2)

Variable that can be accessed inside the


main() function or the function that
LOCAL variable declares it.

Example
Declares inside #include <stdio.h>
main() function or any
void getvalue();
other functions void main()
{ int x;
x is a local variable to }
main() function and z
is a local variable to void getvalue()
getvalue() function { int z;
………… 34
}

17
Scope of variable (3)
Example 1:

#include <stdio.h>

int a, b; //global variable


void display();

void main()
{ printf(“\nEnter value of a and b : ”);
scanf(“%d %d”,&a,&b);
display();
}

void display()
{
printf(“Value a is % and b is %d”, a,b);
}
35

Scope of variable (4)


Example 2:
#include <stdio.h>
Output?
int a, b; //global variables
void display();

void main()
{ int c; //local variable
a= 5;
b = 9;
c = 12;
display();
printf(“\nValue c is %d”, c);
}

void display()
{
printf(“\nValue a is %d”,a);
printf(“\nValue b is %d”,b);
printf(“\nValue c is %d”,c);
} 36

18
Scope of variable (5)
Example 3:
#include <stdio.h> Output?
void display();

void main()
{ int c; // local variable
a= 5;
b = 9;
c = 12;
display();
printf(“\nValue c is %d”, c);
}
void display()
{ int a, b; //local variables
printf(“\nValue a is %d”,a);
printf(“\nValue b is %d”,b);
}
37

Scope of variable (6)


Example 4:
#include <stdio.h> void function1()
{
void function1(); int i,j ;
i= 3;
void function2();
j = i;
int z; printf(“\nValue i is %d”,i);
printf(“\nValue j is %d”,j);
void main() }
{
function1(); void function2()
x= 7; {
z = 15; int x = 4;
z = j;
function2();
printf(“\nValue x is %d”,x);
} printf(“\nValue z is %d”,z);
}
z is a global variable, so it
can be used by any function 38
including main()

19
Types of function
1. Does not receive and not return value
2. Receive but does not return any value
3. Receive and return value

Format

function type function_name (parameter_list);

Determine whether Determine whether


function returns a value functions receive a value

39

Types of function (2)


1. Function that does not receive and not
return value
Example:
void function1(void);

not return value not receive value

void function2(void);

not return value not receive value

40

20
Types of function (3)
Example:

Prototype: #include <stdio.h>


void input();
void input(); //function prototype
Call:
input(); void main()
{
Definition: input(); //function call
}
void input()
{ printf(“Enter input :”); //function definition
scanf(“%d”,&input); void input()
} { printf(“Enter input :”);
scanf(“%d”,&input);
}
41

Types of function (4)


2. Function that receive but does not
return any value

Example:
void function1(int);

not return value receives integer value

void function2(int,int);

not return value receives two integer values

void function3(int,float,int);

not return value receives two integers and a float


values 42

21
Types of function (5)
Example 1:

Prototype: #include <stdio.h>


void function1(int);
void function1(int);
Call:
function1(a); void main()
{ int a ;
Definition: printf(“Enter value :”);
scanf(“%d”,&a);
void function1(int a) function1(a);
{ printf(“Value a is %d”,a); } }

void function1(int a)
{ printf(“Value a is %d”,a); }

43

Types of function (6)


Example 2:

Prototype: #include <stdio.h>


void print_discount(int);
void print_discount(int);
void main()
Call: { int quantity;
print_discount(quantity); printf(“Enter quantity : ”);
scanf(“%d”,&quantity);
Definition: print_discount(quantity);
void print_discount(int b) }
{ if (b > 1000) void print_discount(int b)
printf(“Discount = 50%”); { if (b > 1000)
else printf(“Discount = 50%”);
printf(“Discount = 10%”); else
} printf(“Discount = 10%”);
} 44

22
Example 3
#include<stdio.h> void substraction(int c,int d)
{
void addition(int r,int s); int substract;
substract=d-c;
void substraction(int c,int d);
printf("\nResult of substraction\t"
void multiplication(int e,int f); "%d - %d = %d",d,c,substract);
void division(int m,int n); }

void main(){ void multiplication(int e,int f)


int num1,num2; {
int multiply;
printf("\n Enter two numbers");
multiply=e*f;
scanf("%d%d",&num1,&num2); printf("\nResult of multiplication\t"
addition(num1,num2); "%d * %d = %d",e,f,multiply);
substraction(num1,num2); }
multiplication(num1,num2);
division(num1,num2); void division(int m,int n){
int divide;
}
divide=m/n;
printf("\nResult of division \t"
void addition(int r,int s) "%d / %d = %d",m,n,divide);
{ }
int add;
add=r+s;
printf("\nResult of addition\t"
"%d + %d = %d",r,s,add);
}

45

Types of function (7)


3. Function that receives and returns
value

Example:
int function1(int);

returns value receives integer value

float function2(int,int);

returns value receives two integer values

int function3(int,float,int);

returns value receives two integers and a float


values 46

23
Types of function (8)
Prototype: #include <stdio.h>
float calculate_discount(int); float calculate_discount(int);

void main()
Call: { int quantity;
calculate_discount(kuantiti); printf(“Enter quantity :”);
scanf(“%d”,&quantity);
Definition: printf(“Discount %d”,calculate_discount(quantity));
}
float calculate_discount(int b)
float calculate_discount(int quantity)
{ if (b > 1000)
{
discount = 0.5; float discount;
else if (quantity > 1000)
discount = 0.1; discount = 0.5;
return discount; else
} discount = 0.1;
return discount;
}

return statement 47

Exercise
• Modify Example 3 (Slide 45) from a
program that consist of functions that
receive but does not return any value to a
program that consist of functions that
receive and return value.

48

24
Exercises
A. Give the function prototype for each of the following:
• Function smallest that takes three integers, x, y, z
and returns an integer.
• Function instructions that does not receive any
arguments and does not return a value.
• Function inToFloat that takes an integer argument,
number, and returns a floating-point result.

49

What is the output of this program?


#include<stdio.h>
void change1(int);
int change2(int);
void main()
{
int a=5;
int b;
printf(“Before change1: a=%d\n",a);
change1(a);
printf(“After change1: a=%d\n",a);
b=change2(a);
printf(“After change2: a=%d b=%d\n",a,b);
}

void change1(int a)
{
a=2*a;
printf(“Value of a in change1 function: %d\n",a);
}

int change2(int b)
{
int a;
a=4;
b=a + b;
return (b); 50
}

25
/* Program for Lesson 5_4 */ Function prototype. The * indicates that to work with
the value of the corresponding argument in the
#include <stdio.h> function call, we must use * in the function body

void function1 (int a, int b, double r ,double s, int *c, double *t);
void main (void)
{
int i=5, j=6, k;
double x=10.6, y=22.3, z;

printf (" i = %d \n\r j = %d \n\r x = %lf \n\r y = %lf \n\n",i,j,x,y);


In the function call, we must use & for the k and z.
function1 (i,j,x,y,&k,&z); They are the arguments that have * in the prototype.

printf (" k = %d \n\r z = %lf \n\n", k, z);

void function1 (int a,int b,double r,double s,int *c,double *t)


{
*c = a+b;
*t = r+s +(*c);

printf (" *c = %d \n\r *t = %lf \n\n", *c, *t );


51
} In the function body, we must use * to work with the values

Symbol ‘&’
- An operator that means “address of”
Symbol ‘*’
- 1. the binary multiplication operator
d=e*f;

- 2. The declarator specifier indicating that an


address is to be stored in a variable’s
memory cell
void function1 (int a, int b, double r ,double s,
int *c , double *t);

- 3. The unary operator indicating to go to the


address
*c = a+b;
*t = r+s +(*c);
52

26
/* Program for Lesson 5_5 */

#include <stdio.h>

void function1 (int a, int b, double r, double s, int *c, double *t);

void main (void)


{
int i=5,j=6,k;
double x=10.6,y=22.3,z;

printf (" i = %d \n\r j = %d \n\r x = %lf \n\r y = %lf \n\n",


i,j,x,y) ;

function1 (i,j,x,y,&k,&z);

printf (" k = %d \n\r z = %lf \n\n", k, z) ;

printf (" Address of k = %p\n\r Address of z = %p \n", &k, &z);

void function1 (int a,int b,double r,double s, int *c,double *t)


{
*c = a+b;
*t = r+s+(*c);

printf (" *c = %d \n\r *t = %lf \n\n", *c, *t );


printf (" Value contained in c = %p\n\r"
" Value contained in t = %p\n\n", c, t); 53
}

int i=5,j=6,k;

double x=10.6,y=22.3,z;

Variable Variable Variable Variable


name type address value
i int FFF4

j int FFF2

k int FFF0

x double FFE8

y double FFE0

z double FFD8

Notes: C is responsible for creating the variable address. You need not 54
specify the addresses; they are taken automatically.

27
function1 (i,j,x,y,&k,&z);

void function1 (int a,int b,double r,double s, int *c, double *t)

Variable Variable Variable Variable Variable Variable


name address name type address value

i FFF4 a int FFC0

j FFF2 b int FFC2

x FFE8 r double FFD4

y FFE0 s double FFC4

k FFF0 c address to FFCC


int
z FFD8 t address to FFD6
double
55

*c = a+b;
/*5+6 is stored in the location indicated by the left inside
(go to address contained in c’s memory cell*/
*t = r+s+(*c);
/*10.6+22.3 +11 is stored in the location indicated by the
left inside (go to address contained in t’s memory cell*/

Variable Variable Variable Variable Variable Variable Variable


name type address value name address value
a int FFC0 5
i FFF4 5
b int FFC2 6
j FFF2 6

r double FFD4 10.6


x FFE8 10.6

s double FFC4 22.3 y FFE0 22.3

c address to FFCC FFF0 k FFF0 11


int
t address to FFD6 FFD8 z FFD8 43.9
double
56

28
Revise the
application
programs in
text book!!!

57

29

You might also like