Lecture 8 - Function Part

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 28

Lecture 8

Function (Part I)
Topics will be discussed :-

1. What is a function ?
2. C++ standard library function and
programmer defined function
3. Function declarations , definitions and call function
4. Passing argument and returning values

Everything should be made as simple as possible but not simpler


- Albert Einstein-
What is a function (Fungsi)?

•A function is a subprogram that is executed by being called from within another


function (driver program)
•Every C++ program must include at least a function named main ( )
•Functions allows program modularization which is essential for good software
development
C++ standard library function : e.g. sqrt ( ) sin ( )
(built-in / predefined) pow ( ) toupper ( )
strcmp ( ) rand ( )
log ( ) time ( )

Programmer defined functions : Functions written by programmers

Why use function ?


BECAUSE ……..
1. Functions allow the the programmer to modularize a program (subprogram).
2. Functions can be used / called at many point in a program.
Program

Program without Input 2 nombor


function Kira Hasil darab
Kira Hasil bahagi
Kira Hasil tambah
Cetak semua jawapan

Program / Driver Program


Program with
function Input 2 nombor
Panggil Subprogram 1
Panggil Subprogram 2
Panggil Subprogram 3
Cetak semua jawapan

Subprogram1 untuk Subprogram 2 untuk Subprogram 3 untuk


mencari Hasil darab mencari Hasil bahagi mencari Hasil tambah
Program (driver program)

Input 2 nombor
Panggil Subprogram 1
Panggil Subprogram 2
Panggil Subprogram 3
Cetak semua jawapan
Input 2 Nombor
Panggil Subprogram 2
Cetak jawapan
Input 2 Nombor
Panggil Subprogram 3
Panggil Subprogram 1
Cetak jawapan
(Using Function)
# include <iostream>
# define pi 3.14 Example : Read radius of 4 circles. Calculate
using namespace std; and print the area of each circle in
function CALCULATE ( )
void CALCULATE ( );

int main ( )
{
int m;
for ( m =0; m<4;++m)
{
CALCULATE ( );
}
return 0;
}
void CALCULATE ( )
{
double r,a;
cin >> r;
a=pi*r*r;
cout <<“ Radius = “ << r <<“\tArea = “ << a;
cout <<endl;
}
Typical C++ program with function 3 important elements when
using function in any program
# include <header file>
1. Function Prototype
/* Declaration of Function Prototypes */ 2. Function Definition
void A (void ); 3. Call
(Placement of Function)
void main ( )
{
Local variable declaration for main ( )
A ( ) ; /* call function A */ Local variable ?
within function main ( ) / Driver All variables declared in
program function definition and are
} known only in the function
which they are defined.
/* Function Definitions */
void A (void ) Global variable ?
{ Declared outside any function
Local variable declaration for A ( ) and retain their value throughout
statements ; /* Operasi yang akan the execution of the program
dilaksanakan */
}
Write a driver program to get 2 positive integers A and B. Call a function to
compute and print C . C= A - B2
sqrt(B)

Example program without function Example program with a function

# include <iostream> # include <iostream>


# include <cmath>
# include <cmath>
void CAL(int a , int b);
using namespace std;
int main ( )
int main ( ) {
{ 1 int A,B;
int A,B; 2 cin >> A >> B;
double C; 3 CAL (A,B);
cin >> A >> B; 7 cout << “End of Program” ;
C= (A/sqrt(B)) – pow (B,2) return 0;
cout << C << endl; }
return 0; void CAL ( int a , int b )
} {
Note 4 double C;
5 C = (a/sqrt(b)) – pow (b,2) ;
Input , calculation and print in 6 cout << C << endl;
one driver program : main ( ) }
Function Prototype

A function prototype tells the C++ Compiler :-


- The data type of the function returned value
- The function name
- Information about the arguments (input/output) that the function expects.

e.g. void PROCESS ( void )


• Function PROCESS does not have any argument and does not return
a value

void COUNT (int b)


• Function COUNT with one input argument (int type) and does not return
a value

double SUM (int n , double m)


• Function SUM with 2 input argument (int and double type) and return
a single result (double type)

void KIRA ( int a , int b , double *valuesqrta , double *valuesqrtb)


• Function KIRA with 2 input arguments ( int type ) and 2 output arguments
which carry 2 result (double type)
Function Definition

• Function prototype does not specify the function operation.


• To do this , we need to provide a definition for each function subprogram.

e.g void CAL ( int a , int b ) This subprogram will receive


{ 2 inputs (int type). Do the process
double C; => and print out the output. And
C = (a/sqrt(b)) – pow (b,2) ; because of the data type in this
cout << C << endl; function is void , so it will not
} return any value.

double CAL ( int a , int b ) This subprogram will receive


{ 2 inputs (int type). Do the process
double C; and return a single value to the
=>
driver program which made the call.
C = (a/sqrt(b)) – pow (b,2) ;
Because of the function data type
return C ; is double , so it will return a value
} with double type. The keyword
return must written there.
Call / Placement of function

The order of the program execution is determined by the order of execution of the
function call statement within driver program

How to call a function from driver program ?

Type of Function / Function Prototype Call Statement


void PROCESS ( void ) => PROCESS ( ) ;
void COUNT (int a) => COUNT ( b ) ;
=> S = SUM( x , y ) ;
double SUM (int n , double m)
return ( S ) ; { definition}
void KIRA ( int a, int b, double *va1, double *va2) => KIRA ( a, b, &v1, &v2 ) ;

void KIRA ( int a, int b, double &va1, double &va2) => KIRA (a , b , v1 , v2 );

Call by value e.g. COUNT (b)


Call by reference e.g. KIRA ( a , b , &v1 , &v2 )
TYPE OF FUNCTIONS

1. Function without argument and do not return any value

e.g. void KIRA ( void)

2. Function without argument and return a single value

e.g. int KIRA (void)

3. Function with input argument(s) and do not return any value

e.g. void KIRA (int a , double b , int c )

4. Functions with input argument(s) and return a single value

e.g double KIRA (char a , int b)

5. Functions with input argument(s) and output arguments

e.g. void KIRA (double a , double *sqa , double *sqrta )


e.g # include <iostream>
Input
# include <cmath>
# include <iomanip>
77 7
using namespace std; 33 3
void CAL(int a , int b);
int main ( )
{ Output
int A,B,C,D; -19.9
cin >> A >> B; 10.05
CAL (A,B);
cin >> C >> D;
CAL (C,D);
return 0;
} Note
- actual parameters ( call )
void CAL ( int a , int b )
{ A B
double C; - formal parameters ( definition)
C = (a/sqrt(b)) – pow (b,2) ; a b
cout << setprecision(4) <<C << endl;
}
Example

1 a. Describe star_line as a function with no result and no argument


b. Calls function star_line

2. a. Describe average as a function with a type double result and two


input arguments one type int and one type double
b. Calls function average to compute a result which is stored in money

3. a. Write a prototype for a function called script that has three input argument ,
one char type , one int type and one double type. script will return a result
of type char.
b. Write call statement for function script

4. a. Describe SEARCH as a function with no argument and return an int type


result
b. Write call statement for SEARCH

Perhaps the most valuable result of all education is the ability to make yourself do the thing you
have to do ,when it ought to be done , whether you like it or not. This is the first lesson to be learned.
- Thomas Huxley -
Function with input parameter

This type of function will receive input(s) and can return / not return a single value.

Input Output
Function

Input1 Output
Function
Input2

Input
Function

Input1
Function
Input2
Contoh 1

Given the lengths a , b , c of the sides of a triangle. Write a function to compute


the area A of the triangle. The formula for computing A is given by

A= s ( s  a )( s  b)( s  c)

where s is the semiperimeter of the triangle. Write a driver program to get values for
a , b and c and call your function to compute A. The driver should print A , a , b , and
c

a c
s = (a+b+c)
2
b

Practice does not make perfect ;


perfect practice makes perfect
- Vince
Lombardi -
Example 1

Bina satu aturcara yang mempunyai 3 subaturcara fungsi iaitu :

LUAS ( ) : Untuk mengira luas bulatan


LILITAN ( ) : Untuk mengira perimeter bulatan
CETAK ( ) : Membuat cetakan output
cth cetakkan

Jejari bulatan : 4 m
Luas bulatan : 50.24 m2
Perimeter bulatan : 25.12 m

Semua fungsi dipanggil dari driver program yang sama iaitu main( )
Jejari (meter) adalah input data yang dimasukkan melalui driver program
#include <iostream> double LILITAN (double j)
#include <iomanip> {
#define pi 3.14 return (2 * pi * j );
}
double LUAS (double j);
double LILITAN (double j);
void CETAK(double Luas , double Perimeter ); void CETAK(double Luas , double PR,
double j )
int main () {
{ cout <<“Jejari Bulatan = “ << j <<“ m”;
double r,A,P; cout <<“\nLuas Bulatan = “ <<Luas <<“ m2” ;
cin >> r; cout <<“\nPerimeter Bulatan = “ <<PR<<“ m”;
A=LUAS ( r ); }
P=LILITAN ( r );
CETAK (A , P , r );
return 0;
} Input
4
double LUAS (double j) Output
{ Jejari Bulatan = 4 m
return ( pi * j * j ); Luas Bulatan = 50.24 m2
} Perimeter Bulatan = 25.12 m
Example 2

1. Write a function that returns the smallest of three floating point numbers.
The program should prompt the user whether they want to try another 3
set of floating point number. If yes , call the function , repeat until the
user’s response is no
Example Output

Enter 3 Floating point number3 : 25.87 390.56 19.50

Number 1 : 25.87
Number 2 : 390.56
Number 3 : 19.50

Smallest number is 19.50

Try another set ? Y/N ? : Y

Enter 3 Floating point number3 :

……..etc…….
Solution ex 2
double smallest (double a,double b,double c)
# include <iostream>
# include <iomanip> {
using namespace std; double s;
double smallest (double a,double b,double c); if (a<b)
s=a;
int main () else
{ s=b;
double A,B,C,SMALL; if (c<s)
char ans='Y';
s=c;
while (ans == 'Y' || ans == 'y')
{ return s;
cout <<"\n\nEnter 3 Floating Point Numbers : "; }
cin >> A>>B>>C;
SMALL = smallest(A,B,C);
cout <<"\nNumber 1 : "<<setprecision(4)<<A;
cout <<"\nNumber 2 : "<<setprecision(4)<<B;
cout <<"\nNumber 3 : "<<setprecision(4)<<C;
cout <<"\n\nSmallest Number is : "<<SMALL;
cout <<"\n\nTry Another Set ? Press Y to continue”
cout <<“\nPress any key to exit...: " ;
cin >> ans;
}
return 0;
}
Call by value
- A copy of argument is made and passed to the called function
- Changes to the copy do not effect the original variable’s value in the caller (driver
program)
- e.g. kira(x,y)

Call by reference
- passing addresses
- The caller (driver program) gives the called function the ability to access the
caller’s data directly and to modify the data
- e.g. swap(&x,&y );
Contoh 3
Buat satu aturcara yang boleh mendapatkan kuasa dua , kuasa tiga dan kuasa empat bagi
satu nombor (double ) yang dibaca melalui driver program – main ( ) . Bina satu fungsi
yang akan mendapatkan kuasa 2,3,dan 4 bagi nombor tersebut. Semua cetakan output
hendaklah buat di dalam main ( )

Input
4.5

Output
Kuasadua bagi 4 ialah 20.25
Kuasatiga bagi 4 ialah 91.125
Kuasaempat bagi 4 ialah 410.063
Penyelesaian #include <iostream>
Contoh 3 #include <iomanip>
#include <cmath>
using namespace std;

void Proses (double n , double &x, double &y , double &z);

int main ()
{
double Nombor ,K2,K3,K4;
cin >> Nombor;
Proses ( Nombor , K2 , K3 , K4 );
cout <<“Kuasadua bagi “ <<Nombor <<“ ialah “ << K2;
cout <<“\nKuasatiga bagi “ <<Nombor <<“ ialah “ << K3;
cout <<“\nKuasaempat bagi “ <<Nombor <<“ ialah “ << K4;
return 0;
}

void Proses (double n , double &x, double &y , double &z)


{
x = pow(n,2);
y = pow(n,3);
z = pow(n,4);
}
Latihan : Berikan Output bagi aturcara dibawah

#include <iostream>
#include <iomanip> Output

void sum (int a , int b , int &cp);


5 6
int main () 5 6
{ 5 6
int x , y , z ; 17 6
x = 5 ; y = 6; cout <<x<<y <<endl;; 22 6
sum (x , y , z); cout <<x<<y <<endl; 22 12
sum (y , x , z); cout <<x<<y <<endl;
sum (z , y , x); cout <<x<<y <<endl;
sum (z , z , x); cout <<x<<y <<endl;
sum (y , y , y); cout <<x<<y <<endl;
return 0;
}

void sum (int a , int b , int &cp)


{
cp = a + b;
}
Contoh 4
Buat satu aturcara yang akan mencetak 2 nombor berjenis integer yang dibaca kedalam 2
pembolehubah. Bina satu fungsi swap( ) yang akan melaksanakan penukaran 2 nilai
pembolehubah itu dan seterusnya mencetak nilai yang telah ditukar.
Output
x=5 y = 10
x = 10 y = 5
#include <iostream>
#include <iomanip>
using namespace std;
void swap (int &a,int &b);

int main ()
{
int x , y;

x = 5 ; y = 10;
cout <<"x = "<<x<<"\t"<<"y = "<<y <<endl;
swap(x,y );
cout <<"x = "<<x<<"\t"<<"y = "<<y <<endl;
return 0;
}
void swap (int &a, int &b )
{
int temp = 0 ;
temp = a ;
a=b;
b = temp ;
}
Tugasan 3

a) Computers are playing an increasing role in education. Write a function


that will help an elementary school student learn multiplication. Use rand ( )
to produce two positive one digit integers in one driver program. Call the
function and it should then type a question such as

How much is 6 x 7 ?

The student then types the answer. Your function checks the student’s answer.
If it is correct , print “Very Good” , if the answer is wrong , print “No ,
Please try again ” and let the student try the same question again repeatedly
until the student finally gets its right.
From the driver program , prompt the student if he would like to try another
question. If yes , ask another multiplication question and if not , exit the
program.
b) Write a program for an Automatic Teller Machine that dispenses money.
The user should enter the amount desired and the machine dispenses this
amount using the least number of bills. The bills dispensed are 50s ,10s
and 1s. Write a function that will determine how many each kind of
bill to dispense.

Write a driver program to get amount desired. Your driver program also
should print the output (the number of each bill to dispense.)

Example Input 126.00

Example Output 50 bill : 2


10 bill : 2
1 bill : 6

You might also like