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

FP - Topic 4 - Function and Struct

Bài 4 - Cơ sở lập trình trường Đại học Khoa Học Tự Nhiên
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

FP - Topic 4 - Function and Struct

Bài 4 - Cơ sở lập trình trường Đại học Khoa Học Tự Nhiên
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

University of Science, VNU-HCM

Faculty of Information Technology

Fundamentals of Programming

Function and Struct

Lecturer: Le Ngoc Thanh


Email: [email protected]

Rev.240901
HCM City 1
Content
• Function
– Syntax
– Pass arguments
– Overloading
– Recursion
• Program Organization
• Struct

2
Problems
• Write the program to calculate S = a! + b! +
c!, where a, b, c are positive integers.

main()

Enter Calculate
Output S
a, b, c > 0 S = a! + b! + c!

Enter Enter Enter Do Do Do


a>0 b>0 c>0 s1=a! s2=b! s3=c!

3
Problems
• Code segments to enter intergers a, b, c > 0

do {
printf(“Enter a positive interger a: ”);
scanf(“%d”, &a);
} while (a <= 0);

do {
printf(“Enter a positive interger b: ”);
scanf(“%d”, &b);
} while (b <= 0);

do {
printf(“Enter a positive interger c: ”);
scanf(“%d”, &c);
} while (c <= 0);
4
Problems
• Code segments to calculate factorials: s1 =
a!, s2 = b!, s3 = c!
{ Calculate s1 = a! = 1 * 2 * … * a }
s1 = 1;
for (i = 2; i <= a ; i++)
s1 = s1 * i;

{ Calculate s2 = b! = 1 * 2 * … * b }
s2 = 1;
for (i = 2; i <= b ; i++)
s2 = s2 * i;

{ Calculate s3 = c! = 1 * 2 * … * c }
s3 = 1;
for (i = 2; i <= c ; i++)
s3 = s3 * i;
5
Problems
• Solution => Write one and run anywhere
– The general code for entering numbers, where n
= a, b, c
do {
printf(“Enter a positive integer: ”);
scanf(“%d”, &n);
} while (n <= 0);

– The general code for calculating factorials,


where n = a, b, c
{ Caculate s = n! = 1 * 2 * … * n }
s = 1;
for (i = 2; i <= n ; i++)
s = s * i;
6
Function
• Concepts
– A program segment has a name, input and
output.
– Functions to solve some problems specific to
the main program.
– Called multiple times with different parameters.
– Used when needed:
▪ Reuse.
▪ Bug fixes and improvements.

7
Built-in Functions
• Built-in functions are that type of functions
which are already defined or created in a
program or in programming framework .
• User don’t need to create these type of
functions.
• User or developer can directly use built-in
function by only call it :
– Standard input/output functions: printf(), scanf(), …
– Mathematical functions: sqrt(), pow(), abs(), sin(), …
–…
8
Function Syntax
• Syntax
<return_type> <function_name>([<parameters>])
{
<statements>
[return <value>;]
}
where
▪ <return_type> : any type of C/C++ (char, int, long,
float,…). If you don’t want to return any value, the return
type is void.
▪ <function_name>: follows naming rules.
▪ <parameters> : arguments receive values from caller,
each is separated by comma (,). Declare syntax is similar
with variable declaration.
▪ <value> : is result give back caller by using return
command.
9
How to write function
• List some important information:
– Function name.
– Purpose of function.
– Parameters (if any).
– Return Value (if any).

Parameter 1
Function Name
Parameter 2 Return Value
List task to do
Parameter n

10
How to write function
• Example 1
– Function name: Sum1
– Task: sum of 2 integers and display result on
console screen
– Input: two integers x and y
– Output: none
void Sum1(int x, int y)
{
int s;
s = x + y;
printf(“%d add %d equal %d”, x, y, s);
}

11
How to write function
• Example 2
– Function name: Sum2
– Task: calculate sum of 2 integer numbers and
return result
– Input: two integers x and y
– Output: return an integer which is result of x + y
int Sum2(int x, int y)
{
int s;
s = x + y;
return s;
}

12
How to write function
• Example 3
– Function name: Sum3
– Task: enter 2 integers and display sum of them
on console screen.
– Input: none
– Output: none
void Sum3()
{
int x, y;
printf(“Enter 2 integer numbers: ”);
scanf(“%d%d”, &x, &y);
printf(“%d add %d equal %d”, x, y, x + y);
}
13
Scope
• Concept
– Scope refers to the visibility of variables.
– Variable:
▪ Global: the declaration is made outside all functions
(including the main function) and has an effect on the
entire program.
▪ Local: The declaration is placed within a function or
block {} and only works within the function or block
itself (including its children).
– The local variable is deleted from memory at the end of its
declaration block.

14
Scope

int a;
int Func1()
{
int a1;
}

int Func2()
{
int a2;
{
int a21;
}
}

void main()
{
int a3;
}
15
Notes
• Normally we should put the function header /
function prototype on the main function and
the function definition below the main
function.
void Sum(int x, int y); // prototype

void main()
{

}

void Sum(int x, int y)


{
printf(“%d plus %d equal %d”, x, y, x + y);
}
16
Pass Arguments
• Call by Value
– Pass arguments to functions as values.
– It is possible to pass constants, variables,
expressions, but functions will only take values.
– Used when there is no need to change the value
of a parameter after function execution.

void CallByValue(int x)
{

x++;
}

17
Pass Arguments
• Call by Address
– Pass the argument to the function as an
address (pointer).
– Do not pass a value for this parameter.
– Used when there is a need to change the value
of a parameter after function execution.

void CallByAddress(int *x)


{

*x++;
}

18
Pass Arguments
• Call by Reference (C++)
– Pass the argument to the function as an
address (pointer). Start with the & sign in the
declaration.
– Do not pass a value for this parameter.
– Used when there is a need to change the value
of a parameter after function execution.
void CallByReference(int &x)
{

x++;
}

19
Notes
• Caution:
– In a function, parameters can be passed in
several ways.

void MixCall(int x, int &y)


{

x++;
y++;
}

20
Notes
• Using reference is a way to return the value
to the caller.
int Sum1(int x, int y)
{
return x + y;
}
void Sum2(int x, int y, int &mySum)
{
mySum = x + y;
}
void SumAndDiff(int x, int y, int &mySum, int &myDiff)
{
mySum = x + y; myDiff = x – y;
}

21
Function Call
• Syntax:
– Calling the function's name and simultaneously
passes arguments (constants, variables,
expressions) to the parameters in the order
declared in the function.
– These variables or values are separated by
comma (,)
– These arguments are enclosed in parentheses ().
<function name> (<argument 1>, ..., <argument n>);
– The argument itself can also be another function
call
22
Examples

{ Functions are declared here }


void main()
{
int n = 9;
Sum1(1, 2);
Sum1(1, n);
Sum2(1, 2);
int result = Sum2(1, 2);
CallByValue(1);
CallByValue(n);
CallByAddress(1);
CallByAddress(&n);
CallByReference(1);
CallByReference(n);
}

23
Examples

void Swap(int &a, int &b);

void main()
{
Swap(2912, 1706);
int x = 2912, y = 1706;
Swap(x, y);
}
void Swap(int &a, int &b)
{
int tempt = a;
a = b;
b = tempt;
}

24
Example
void DoSomething();
int Sum(int x, int y);
void main() {
DoSomething();
Sum(1, 2); // the return value is discarded
int x = Sum(1, 2);
int y = Sum(1, Sum(2, 3));
printf(“%d\n”, Sum(1, 2));
}
// defines DoSomething() and Sum() here…

25
Notes
• If you try to use functions with the return
type void as an expression, the compiler will
generate an error message.
void DoSomething();
void main() {
DoSomething();
int x = DoSomething(); // error
printf(“%d\n”, DoSomething()); // error
}
// defines DoSomething() here…

26
Notes
• It is possible to write functions with the same
name, except for the number and properties
of the arguments.
int Sum() { // non generic
int x, y;
// inputs x, y here…
return x + y;
}
int Sum(int x, int y) { // generic and thus reusable
return x + y;
}

27
Exercise
• Create two functions:
– One that swaps two numbers using pass-by-
value
– Another that swaps them using pass-by-
reference.

28
Exercise
• Write a function that calculates the area of a
rectangle.
– Use default arguments for width and height.

29
Function Overloading
• Overloading allows defining multiple
functions with the same name but different
parameter lists (number or types of
parameters).
– Supported in C++, but not in C.
• Perpose?
– Increases the flexibility of the code.
– Allows reusing the same function name for
different tasks based on parameters.

30
Example

31
Recursive Function
• Recursive function is:
– A function may call itself.
– The number of calls must be limited.
▪ If not, stackoverflow
• Example
– Calculate S(n) = n! = 1*2*…*(n-1)*n
– Because S(n) = S(n-1)*n
– So we can calculate S(n) through S(n-1)
– Similar for S(n-2), …, S(2), S(1), S(0) = 1

32
Recursive Function
• Example

int Factorial(int n)
{
if (n == 0)
return 1;
else
return Factorial(n – 1) * n;
}
int Factorial(int n)
{
if (n > 0)
return Factorial(n – 1) * n;
else
return 1;
}
33
Exercise
• Write a recursive function to calculate the
nth Fibonacci number in the Fibonacci
sequence.
• Write a recursive function to calculate the
sum of digits of a given number.

34
Exercises
1. Write program with some functions:
a. Converts a capital letter to lowercase.
b. Solve first order equations.
c. Solving quadratic equations.
d. Returns the smallest value of 4 integers.
e. Permutation of two integers.
f. Arranging 4 integers in ascending order.

35
Exercises
2. Write program with some functions which
receive the positive integer number n as
argument:
a. Returns the reverse of that number.
b. Is the number of symmetry (Returns True / False)
c. There must be the square root.
d. There must be prime numbers.
e. Sum of odd digits.
f. Sum of prime numbers.
g. Sum of square digits.
36
Exercises
3. Write program with some functions which
receive the positive integer number n as
argument:
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!
4. Write the function that returns the greatest
common divisor of 2 integers.
5. Write the function that prints out n elements of the
Fibonacci sequence.
37
Content
• Function
• Program Organization
• Struct

38
Multiple-file project
• Organize C/C++ project:
– Like a book:
▪ Chapters ~ source code files.
▪ Summary ~ main() function.
➔ How to connect multiple source code files?
// File main.cpp // File io.cpp // File compute.cpp
int main() void input() int compute1()
{ { {
input(); } }
compute1();
compute2(); void output() int compute2()
output(); { {
} } }

39
Multiple-file project
• Header file:
– Connect source files across project.
– Make code on a file “see” code on another file.
– File extension .h.
– Usage:
▪ Create header file .h for source file .cpp.
▪ File .h contains only declaration (global
variables/functions).
▪ File .cpp contains implementation of functions.
▪ To let A.cpp “see” code in B.cpp
➔ A.cpp #include “B.h”
40
Multiple-file project
• Header file:
// File main.cpp // File io.h // File compute.h
#include “io.h” // Function declaration // Function declaration
#include “compute.h” void input(); int compute1();
void output(); int compute2();
int main()
{
input();
compute1(); // File io.cpp // File compute.cpp
compute2(); #include “io.h” #include “compute.h”
output(); void input() int compute1()
} { {
} }
void output() int compute2()
{ {
} }

41
Multiple-file project
• Divide-conquer a project:
– How to eat a cow?
➔ Split into small parts.
➔ Eat each parts.
– How small is small?
➔ Can be chewed.
– Organize a project:
▪ Split into functions and files.
▪ Implement each function.
▪ Should be < 30 statements.

42
Multiple-file project
• Program breakdown tree:
– Enter 3 positive integers a, b, c >= 0.
– Compute and print S = a! + (b + 1)! + (c + 2)!.
Program

Input Compute Output

Input
Factorial
positive int

Fundamentals of Programming - Nguyễn


Minh Huy 43
Multiple-file project
// File process1.h // File process2.h
void input(int &a, int &b,int &c); void input_num(int x);
long compute(int a, int b, int c); long factorial(int n);
void output(long result);
// File main.cpp // File process1.cpp // File process2.cpp
#include “process1.h” #include “process1.h” #include “process2.h”
#include “process2.h” #include <stdio.h>
int main() void input(int &a, int &b,int &c) void input_num(int &x)
{ { {
int a, b, c; input_num(a); do {
long S; input_num(b); printf(“Positive integer = “);
input_num(c); scanf(“%d”, &x);
input(a, b, c); } } while (x < 0);
S = compute(a, b, c); long compute(int a, int b, int c) }
output(S); {
} return factorial(a) + long factorial(int n)
factorial(b+1) + factorial(c+ 2); {
} long S = 1;
void output(long result) for ( ; n > 0; n--)
{ S = S * n;
printf(“S = %ld”, result); return S;
} }
Fundamentals of Programming - Nguyễn
Minh Huy 44
Exercise
• Write a program to check if an integer
entered by the user is a prime number.
• File Organization:
– Create main.cpp to call the functions.
– Create prime.cpp to contain the prime-checking
function.
– Create io.cpp to contain the input and output
functions.
– Create header files prime.h and io.h to declare
respective functions.

45
Content
• Function
• Program Organization
• Struct

46
Problem
• Declare variables to store 1 student
char id[8]; // “20122345”
char fullname[30]; // “Nguyen Van A”
char birthdate[9]; // “01/01/01”
char gender; // ‘n’
float math, physics, chemistry; // 8.5 9.0 10.0

• Passing student information to the function


void output(char* id, char* fullname, char* birthdate, char gender,
float math, float physics, float chemistry);

47
Problem
• How to declare variables to store array of
student information?
char id[100][8];
char fullname[100][30];
char birthdate[100][9];
char gender[100];
float math[100], physics[100], chemistry[100];

48
Problem
• Comments
– Difficult to manage
– Passing too many parameters to the
function
– Finding, sorting, copying,… is complicated
–…
• Idea
– Gather information of the same student
into a new data type => struct type
49
Declare structure type
• Syntax
// Syntax 1: // Syntax 2:
struct <structure_name> { typedef struct
<data_type> <data_1>; {
… <data_type> <data_1>;
<data_type> <data_n>; …
}; <data_type> <data_n>;
} <structure_name>;
• For example
struct Student {
char id[8];
char fullname[30];
char birthdate[9];
char gender;
float math, physics, chemistry;
};

50
Declare variable
• The syntax (directly)
struct <structure_name> {
<data_type> <data_1>;

<data_type> <data_n>;
} <variable_name_1>, <variable_name_2>;

• Example
struct Point2D {
int x;
int y;
} p1, p2;

51
Declare variable
• The syntax (indirectly)
struct <structure_name> {
<data_type> <data_1>;

<data_type> <data_n>;
};
struct <structure_name> <variable_name_1>, <variable_name_2>;

• Example
struct Point2D {
int x;
int y;
};
struct Point2D p1, p2; // C++ the “struct” keyword can be omitted

52
Use typedef
• Synax
typedef struct {
<data_type> <data_1>;

<data_type> <data_n>;
} <structure_name>;
<structure_name> <variable_name_1>, <variable_name_2>;

• Example
tyepdef struct {
int x;
int y;
} Point2D;
Point2D p1, p2;

53
Initialization for structure variables
• Syntax
struct <structure_name> <variable_name> = {<value_1>, <value_2>, …,
<value_n>};

struct <structure_name> <variable_name> =


{ // C99 standard
.<member name> = <value>,

};

• Example
struct Point2D {
int x;
int y;
} p1= {2912, 1706}, p2;

54
Access to elements in the structure
• Syntax
– Through structural component operators.
Also known as the dot operator.
<structure_name>.<data_name>

• Example
struct Point2D {
int x, y;
} p = {2912, 1706};

void show(Point2D p) {
printf(“x = %d, y = %d\n”, p.x, p.y);
}

55
Assign value
• There are 2 methods
<dest_structure_name> = <source_structure_name>
<dest_structure_name>.<data_name> = <value>

• Example
struct Point2D {
int x, y;
} p1 = {2912, 1706}, p2;
void main() {
p2 = p1;
p2.x = p1.x;
p2.y = p1.y * 2;
}

56
Assign value
• struct assignment:
– All struct members are copied.
– Array members are copied too!
struct Student s1 = { .name = “minh”, .literature = 8.0 };
struct Student s2 = s1;

s1: Student s2: Student


▪.name ▪.name
Copy
m i n h \0 m i n h \0
▪.literature ▪.literature
Copy
8 8

57
Exercise 1
• Write a program to identify the center of the triangle with the
following variables:

typedef struct {
double x, y;
} Point2D;

typedef struct {
Point2D ver[3];
} Triangle;

void InputPoint2D(Point2D& p);


void ShowPoint2D(Point2D p);
void InputTriangle(Triangle& t);
void CenterOfGravity(Triangle t, Point2D& p);

58
Solution
void InputPoint2D(Point2D& p) {
cout << “ + Coor X = “; cin >> p.x;
cout << “ + Coor Y = “; cin >> p.y;
}
void ShowPoint2D(Point2D p) {
cout << “(” << p.x << “, ” << p.y << “(”;
}
void InputTriangle(Point2D& p) {
for (int i = 0; i < 3; i++) {
cout << “Vertex ” << i + 1 << “: ” << endl;
InputPoint2D(t.ver[i]);
}
}

59
Solution (cont)
void CenterOfGravity(Triangle t, Point2D& p) {
p.x = (t.ver[0].x + t.ver[1].x + t.ver[2].x) / 3;
p.y = (t.ver[0].y + t.ver[1].y + t.ver[2].y) / 3;
}
void main() {
Triangle t;
Point2D p;
InputTriangle(t);
CenterOfGravity(t, p);
cout << “Center of Gravity of the triangle: ”;
ShowPoint2D(p);
}

60
Exercise 2
• Write a program to caculate with fractions with the
following declaration:

typedef struct {
long numerator;
long denominator;
} Fraction;

void GreatestDivisor(long a, long b);


void Reduce(Fraction& p);
Fraction Add(Fraction p, Fraction q);
Fraction Sub(Fraction p, Fraction q);
void ShowFraction(Fraction p);

61
Solution
void GreatestDivisor(long a, long b) {
// Do by yourself…
}
void Reduce(Fraction& p) {
long gcd = GreatestDivisor(p.numerator, p.denominator);
p.numerator /= gcd;
p.denominator /= gcd;
}
Fraction Add(Fraction p, Fraction q) {
Fraction r;
r.numerator = p.numerator * q.denominator + p.denominator *
q.numerator;
r.denominator = p.denominator * q.denominator;
return r;
}

62
Solution (cont)
Fraction Sub(Fraction p, Fraction q) {
q.numerator = -q.numerator;
return Add(p, q);
}
void ShowFraction(Fraction p) {
Reduce(p); // Simplify the fraction before printing it out
cout << p.numerator << “/” << p.denominator;
}

63
Exercises
1. Write C/C++ program to operate on date:
(organize in functions and multiple-file project):
- Declare struct to represent date (day, month, year).
- Enter two date d1 and d2.
- Check if d1 is latest than d2 and print result.
- Print tomorrow date of d1.
- Print yesterday date of d2.

64
Exercises
2. Describe a struct to store a complex number and build up
a function to add, subtract and multiply two complex
numbers.
3. Describe a struct to store time (hour, minute, second) and
write a function to check time difference.
4. Create student mark list program using struct and array
with some functions:
– Enter a list of student information (student id, number of finished
course, marks in each course)
– Caculate average mark of a student

65
The End

You might also like