0% found this document useful (0 votes)
3 views

4 Functions

The document covers the fundamentals of programming, focusing on decomposition, abstraction, and functions. It explains how to structure code using modules and the importance of functions for reusability, including examples of factorial calculations and parameter passing methods. Additionally, it discusses concepts such as recursive functions, function overloading, and provides exercises for practical application.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

4 Functions

The document covers the fundamentals of programming, focusing on decomposition, abstraction, and functions. It explains how to structure code using modules and the importance of functions for reusability, including examples of factorial calculations and parameter passing methods. Additionally, it discusses concepts such as recursive functions, function overloading, and provides exercises for practical application.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

DECOMPOSITION,

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

• ABSTRACTION IDEA: do not need to know how projector


works to use it
FundamentalsOfProgramming 5
Example – Projector

Input Output

• Projecting large image for Olympics decomposed into separate


tasks for separate projectors
• Each projector takes input and produces separate output
FundamentalsOfProgramming 6
Example – Projector

Input Output

• DECOMPOSITION IDEA: different devices work together to


achieve an end goal FundamentalsOfProgramming 7
CREATE STRUCTURE with
DECOMPOSITION
• In projector example, separate devices

• In programming, divide code into modules


• used to break up code
• intended to be reusable
• keep code organized
• keep code coherent

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

• In programming, think of a piece of code as a black box


• cannot see details
• do not need to see details
• do not want to see details
• hide tedious coding details

• Achieve abstraction with function specifications or docstrings


FundamentalsOfProgramming 9
Example – Sum of three factorial numbers
• Write a program to calculate S = a! + b! + c! from a, b, c input by
users
Main program

Input Calculate Output


a, b, c S = a! + b! + c! the result S

Input Input Input Cal Cal Cal


a>0 b>0 c>0 s1 = a! s2 = b! s3 = c!
FundamentalsOfProgramming 10
Input three numbers > 0
do{
cout << “Input a natural number: “;
cin >> a;
} while (a <= 0);
do{
cout << “Input a natural number: “;
cin >> b;
} while (b <= 0);
do{
cout << “Input a natural number: “;
cin >> c;
} while (c <= 0); FundamentalsOfProgramming 11
Calculate s1, s2, s3
// calculate n! = 1 * 2 * ... * n
s1 = 1;
for (i = 2; i <= a; i++)
s1 = s1 * i;
s2 = 1;
for (i = 2; i <= b; i++)
s2 = s2 * i;
s3 = 1;
for (i = 2; i <= c; i++)
s3 = s3 * i; FundamentalsOfProgramming 12
Functions
• “intended to be reusable” à write one time and use many times
Input a, b, c à Input n (n = a, b, c)
do{
cout << “Input a natural number: “;
cin >> n;
} while (n <= 0);
Calculate a!, b!, c! à Calculate s = n! (n = a, b, c)
s = 1;
for (i = 2; i <= n; i++)
s = s * i; FundamentalsOfProgramming 13
Functions
• Write reusable pieces/chunks of code, called functions
• Functions are not run in a program until they are “called” or
“invoked” in a program
• Function characteristics:
• has a name
• has parameters (0 or more)
• has a docstring (optional but recommended)
• has a body
• returns something (or not)

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

• Some compiler requires return 0 in the main function

• return within a function whose <DataType> is void , means


termination. It can be applied in the main function

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.

Local: placed within functions or blocks {} and affect


only within functions or blocks (or their nested blocks).
Memory of local varialbes will be deallocated after
the functions or blocks that declared them have ended.

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)

• Functions should be independent


• If using global variables within functions, such functions are not
independent

• Using global variables has side effects


• Hard debugging
• Conflicting names of variables of multilple files in a program

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

• Can be passed by constants, variables, expressions but the


functions only pass the values of those

• It is used when we DO NOT want to change values of actual


parameters after functions run

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);

• Do not pass the value for these parameters

• It is used when we want to change values of actual parameters


after functions run

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);

• How about pow function?

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);

int func2(int len = 1, int wid, int hei = 1);

void func3(int x, int& y = 16, double z = 34);

FundamentalsOfProgramming 37
Default Arguments
Invalid default arguments
void func1(int x, double z = 3.14, char y);

int func2(int len = 1, int wid, int hei = 1);

void func3(int x, int& y = 16, double z = 34);

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

You might also like