Professional Documents
Culture Documents
ch6 Functions
ch6 Functions
ch6 Functions
Functions
Function elements:
Types of functions
Objectives
Write a program that can add, subtract, multiply and divide two numbers.
What do you think?
There are so many operations in main().
software reusability –
make program
program structure is using existing functions
development more
readable as building block to
manageable
create new program
Functions elements
Prototype
Call
Definition
– Must be added to a C program
before the main() function, if call that
function before defining it
Prototype
(function return type) expected.
Function
– The first line of a function
Definition definition contains:
FUNCTION DEFINITION
– 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.
FUNCTION
DEFINITION
EXAMPLE
Without prototype
FUNCTION
DEFINITION
EXAMPLE
– 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.
Function
– If the function call does not require any arguments
Calls empty pair of parentheses must follow the name of the function.
Function
If the function returns a value, the function
Calls access is written in a statement; e.g.,
• b = sum(a);
• view(a,b,c);
A function can be In C, functions call
called by can be
Function
Call by reference
Calls
• Pass the address of a variable (i.e. a pointer) to a
function
• The variable pointed to can be modified within that
function
SCOPE OF
VARIABLE
SCOPE OF
VARIABLE
SCOPE OF
VARIABLE
EXAMPLE 1
SCOPE OF
VARIABLE
EXAMPLE 2
OUTPUT?
SCOPE OF
VARIABLE
EXAMPLE 3
SCOPE OF VARIABLE
EXAMPLE 4
Format
value
TYPES OF
FUNCTION
EXAMPLE
return
statement
Modify Example 3 (slide 42) 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.
EXERCISE
Give the function prototype for each of the following:
EXERCISE
EXERCISE
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
Pointer in C 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);
#include<stdio.h>
void function1 (int a, int b, double r ,double s, int *c, double *t);
f u n c t i o n 1 ( i , j , x , y, & k , & z ) ;
}
function1 (i,j,x,y,&k,&z);
void function1 (int a,int b,double r,double s, int *c, double *t)
5 5
6 6
10.6 11
22.3 10.6
FFF0 22.3
FFD8 43.9
#include<stdio.h>
void function1 (int a, int b, double r ,double s, int *c, double *t);