Functions
Functions
Computer Programming
Chapter 4: FUNCTION
Lecture Note
Sem 1, sesi 20202021, FTK
1
Chapter 4: FUNCTION
No. Title Page
1. Definition 3
2. Element in function 4
3. Function categories 5
4. Function calls 10
2
1. Definition
What is function?
Independent program module that is specially written
to implement the requirement of the function
Construct a program from smaller pieces or
components.
Each piece more manageable than the original
program
To organize the program
Reduce the program size
3
2. Element in Function
There are 3 elements in function:
2.1 Function declaration syntax
• To declare the function
• <function type> <function name> (<parameter type>);
• Eg: int add (int a , int b)
2. Function call syntax
• To call the function from main function
• Can be used in main function, other function or itself.
• <function name> (<parameter list>);
• Eg: add (a , b);
3. Function definition syntax
• Can be define as function body
• <function type> <function name> (<parameter type and list>)
{
body of function
}
• Eg:
int add (int a , int b)
{
statement of add function
}
4
3. Function categories
5
3.1 Function with no argument and no return value
Function:
not receive any argument from main()
not return any value to the main()
No return value
6
3.2 Function with argument and no return value
Function:
receive argument from the main()
not return any value to the main()
argument
No return value
7
3.3 Function with no argument and return value
Function:
not receive any argument from the main()
but return the value to the main()
value
8
3.4 Function with argument and return value
Function:
receive argument from the main()
return the value back to the main()
argument
value
9
Comparison function categories
Function Categories
10
4. Function calls
Two ways to call the function:
1. Call by value
• Copies argument value to the function
• Only pass the value
2. Call by reference
• Call by reference
• Pass the address of the value
• Value change in function will change value in the main()
11
Example: please predict output on the screen for both.
12
#include <iostream> #include <iostream>
using namespace std; using namespace std;
13
14
#include <iostream>
using namespace std;
int main()
{
int f,g,d;
cout << "masukkan 2 nombor kerbau = " << endl;
cin>>f>>g;
kerbau(f,g);
d = kerbau(f,g) + 2;
cout<<"d = "<<d<<endl;
cout << "masukkan 2 nombor ayam = " << endl;
cout<<ayam();
cout << "\nmasukkan 2 nombor lembu = " << endl;
cout<<ayam() + lembu()<<endl;
cout<<kerbau(f,g) + ayam()<<endl;
return 0;
}
int kerbau(int a, int b)
{
int c;
c = a +b;
return c;
}
int ayam()
{
int x,y,z;
cin>>x>>y;
z = x + y;
return z;
}
int lembu()
{
int k,l,m;
cin>>k>>l;
m = k + l;
return m;
}
15