4 Functions
4 Functions
ABSTRACTION, FUNCTIONS
Fundamentals of Programming
Bùi Duy Đăng
[email protected]
Plan for today
• Decomposition and Abstraction
• Functions
• Exercises
FundamentalsOfProgramming 2
Decomposition and
Abstraction
FundamentalsOfProgramming 3
Example – Projector
Input Output
FundamentalsOfProgramming 4
Example – Projector
Input Output
HOW IT WORK?
Blackbox
Input Output
Input Output
FundamentalsOfProgramming 8
SUPRESS DETAILS with
ABSTRACTION
• In projector example, instructions for how to use it are sufficient,
no need to know how to build one
FundamentalsOfProgramming 14
Remind: some predefined functions
• For example: Math functions
• What are names, parameters, types returned of the square root
function?
• What are names, parameters, types returned of the power function?
#include <cmath>
// pow(x, y)
double z = pow(2, 3) // type of 2 and 3
// sqrt(x)
z = sqrt(121) // type of 121?
FundamentalsOfProgramming 15
Function
<DataType> FunctionName(<ArgumentList>) {
// body of function
return <value>; // it is optional
}
<DataType> : int, float, double, etc. If no return à void
FunctionName : write a meaningful name (avoid predefined
keywords).
<ArgumentList> : arguments separated by a comma (,). They can
be empty.
<value> : return ONE value by keyword return.
FundamentalsOfProgramming 16
Example - Factorial
• Build a function to calculate factorial of a number n
// given a number n and returns the factorial of n
long long calFactorial(int n){
long long s = 1;
for (i = 2; i <= a ; i++)
s = s * i;
return s;
}
FundamentalsOfProgramming 17
Notes
• main is a function also and it is a place where a program starts
to run
FundamentalsOfProgramming 18
Notes
• Function declaration (prototype)
Should put between library declaration and the main function
<DataType> FunctionName(<ArgumentList>);
long long calFactorial(int);
• Function definition
If we declare prototypes, we should put then after the main function
long long calFactorial(int n){
// ...
FundamentalsOfProgramming 19
}
Notes – Example
long long calFactorial(int); // declaration
int main(){
return 0;
}
long long calFactorial(int n){ // definition
long long s = 1;
for (i = 2; i <= n ; i++)
s = s * i;
return s;
} FundamentalsOfProgramming 20
Scope
FundamentalsOfProgramming 21
Scope
• Refers valid scopes of variables and functions
• Variables:
Global: placed outside of functions (including the main
function) and can affect the entire program.
FundamentalsOfProgramming 22
int a;
int func1(){
int a1;
}
int func2(){
int a2;
{
int a21;
}
}
int main(){
int a3
return 0;
}
FundamentalsOfProgramming 23
Notes
• Global variables are often used as constant variables (const)
FundamentalsOfProgramming 24
Parameter passing
FundamentalsOfProgramming 25
Call-by-Value Parameters
• Parameters passed are values of actual parameters. A program
will clone objects whose values are the same as parameters
passed
FundamentalsOfProgramming 26
Call-by-Reference Parameters
• Parameters passed are addresses of actual parameters. They
start with & in parameter.
E.g., void doSth(int &a); void doSth(int& a);
FundamentalsOfProgramming 27
Call-by-Reference Parameters
It is useful when
returning more than one value,
changing the actual parameter,
saving memory space and time
FundamentalsOfProgramming 28
Example
• A function that swaps two numbers
void Swap1(int a, int b) { // is it working?
int temp;
temp = a; a = b; b = temp;
}
void Swap2(int &a, int &b) { // is it working?
int temp;
temp = a; a = b; b = temp;
}
FundamentalsOfProgramming 29
Recursive Functions
• A program that calls itself
• Must have at least one stopping point (called a base case)
int calFactorial(int n) {
if (n == 0) return 1; // stopping point
else return calFactorial(n – 1) * n;
}
int calFactorial(int n) {
if (n > 0) return calFactorial(n – 1) * n;
else return 1; // stopping point
} FundamentalsOfProgramming 30
Function Overloading
FundamentalsOfProgramming 31
Example – Math funcitons
• How many parameters does the function sqrt require?
<DataType> sqrt(<ArgumentList>);
• What types of these parameters? What types do they return?
float sqrt(float);
double sqrt(double);
long double sqrt(long double);
FundamentalsOfProgramming 32
Overloaded Functions
• Two or more functions have same names but they have
different parameters (types, numbers)
• For example, which ones are invalid? And why?
int test();
void test(int);
void test(float);
int test(float);
float test();
int test(int,int);
FundamentalsOfProgramming 33
Overloaded Functions
• Two or more functions have same names but they have
different parameters (types, numbers)
• For example, which ones are invalid? And why?
int test();
void test(int);
void test(float);
int test(float); // Why cannot?
float test(); // Why cannot?
int test(int,int);
FundamentalsOfProgramming 34
Other topics
• Default Arguments
• Function as an Argument
• Resolution operator (::)
• static data type
FundamentalsOfProgramming 35
Default Arguments
// declaring necessary statements
int sum(int x, int y, int z = 0, int w = 0){
return (x + y + z + w);
}
int main(){
cout << sum(10, 20) << endl;
cout << sum(10, 20, 30) << endl;
cout << sum(10, 20, 30, 40) << endl;
return 0;
} FundamentalsOfProgramming 36
Default Arguments
Invalid default arguments
void func1(int x, double z = 3.14, char y);
FundamentalsOfProgramming 37
Default Arguments
Invalid default arguments
void func1(int x, double z = 3.14, char y);
FundamentalsOfProgramming 38
Default Arguments
test(int a, int b = 7, char z = ’*’);
Which functions are called correctly?
a) test(5);
b) test(5,8);
c) test(6,’#’);
d) test(0,0,’*’);
FundamentalsOfProgramming 39
Function as an Argument
FundamentalsOfProgramming 40
Exercises
1) Write functions to convert a lower case to upper case and vice
versa.
2) Write a funciton to solve first degree equation.
3) Write a function to solve quadratic equation using function 2).
4) Write a function to return the minimum value of 4 integers.
5) Write a function to swap two integers.
6) Write a function to sort 4 integers in an ascending order with
utilizing functions 4) and 5).
FundamentalsOfProgramming 41
Exercises
6) Write functions with input n and do:
a) Return its inverse
b) Whether it is a symmetrical number or not? (return True/False)
c) Whether it is a perfect square number or not?
d) Whether it is a prime number or not?
e) Return sum of odd numbers in n
f) Return sum of prime numbers in n (using function d) )
g) Return sum of perfect square numbers in n (using function c) )
FundamentalsOfProgramming 42
Exercises
7) Write functions with input n and do (using recursion if possible):
a) S = 1 + 2 + … + n
b) S = 12 + 22 + … + n2
c) S = 1 + 1/2 + … + 1/n
d) S = 1*2*…*n
e) S = 1! + 2! + … + n!
8) Write a function returned GCD of two integers
9) Write a function that prints out n elements in the Fibonancci series
FundamentalsOfProgramming 43