Chapter3_Functions and Libraries
Chapter3_Functions and Libraries
© HĐC 2024.1
Content
Data-oriented programming
D_1
Data 1
D_2
Data 2
D_3
Data 3
#include <iostream>
using namespace std;
int ReadInt();
int SumInt(int, int);
void WriteResult(int a, int b, int kq);
void main() {
char c;
do {
int a = ReadInt();
int b = ReadInt();
int T = SumInt(a,b);
WriteResult(a,b,T);
cout << "Do you want to continue? (Y/N):";
cin >> c;
} while (c == 'y' || c == 'Y');
}
#include <iostream.h>
int ReadInt(const char*);
int SumInt(int,int);
void main() {
char c;
do {
int a = ReadInt("Enter the first integer number :");
int b = ReadInt("Enter the second integer number:");
cout << "The sum from " << a << " to " << b
<< " is " << SumInt(a,b) << endl;
cout << "Do you want to continue? (Y/N):";
cin >> c;
} while (c == 'y' || c == 'Y');
}
int x = 5;
int k = SumInt(x,10); Returning value
(no name)
...
Actual
parameters
SumInt
int a = 2; x a
k
k = SumInt(a,x); 10 b
Variable assigned
to returning value
Arguments
} a=5
SP
k = 45
// Function definition
x=5
int SumInt(int a,int b) {
...
#include <iostream.h>
void ReadInt(const char* userPrompt, int N) {
cout << userPrompt;
cin >> N;
}
void main() {
int x = 5;
ReadInt("Input an integer number:", x);
cout << "Now x is " << x;
...
}
Result: x is unchanged
#include <iostream.h>
void ReadInt(const char* userPrompt, int* pN) {
cout<< userPrompt;
cin>> *pN;
}
void main() {
int x = 5;
ReadInt("Input an integer number:", &x);
cout<< "Now x is " << x;
...
}
int a[][MAX_HWS]
Method 1
int main(void)
{
int score[MAX_STUDENTS][MAX_HWS];
int nstudents, nhws;
Method 2
void read_2D (int *a[MAX_HWS],
int nstudents, int nhws) { … }
int main(void)
{
int *score[MAX_HWS];
int nstudents, nhws;
Method 3
void read_2D (int **a, int nstudents, int nhws) { … }
int main(void)
{
int **score;
int nstudents, nhws;
Only in C++
It is required to change “input variables” (access directly
in memory allocation, not via the copy)
A reference argument can be output (consisting of the
result), or both input and output
Size of the argument’ data type is large, thus it can avoid
to copy large data to stack, e.g.:
void copyData (const Student& sv1, Student& sv2) {
sv2.birthday= sv1.birthday;
...
}
45
void main() {
int s[5] = { 1, 2, 3, 4, 5};
int *p = FindMax(s,5);
}
#include <stdio.h>
void callback_func()
{
printf(“I am a call back function”);
}
void f(void (*ptr))
{
ptr(); // a call-back function that p point to
}
int main()
{
void (*p)() = callback_func;
f(p);
}
#include <stdio.h>
Requirement analysis
Clarify assumptions (inputs) and results (outputs)
Figure out features to be implemented
Function naming: short, meaningful, self-described
Action function: a verb + an object, e.g.: printVector, displayMatrix,
addComplex, sortEventQueue, filterAnalogSignal, …
Functions to access properties: a verb or a noun combine with a
specific object, e.g.: length, size, numberOfColumns, getMatrixElem,
putShapeColor
In C++, many functions may have the same name (function
overloading), thus short names can be used, e.g.: sort, print,
display, add, putColor, getColor polymorphism in OOP
In C++, it is possible to define operator which utilizes pre-
defined operator symbol such as *, /, +, - instead of function
calls
Function declaration:
void findPrimeSequence(int N, int* primes);
Design function body:
Flowchart
Use a new function: findNextPrime
Repeat the design steps for findNextPrime function
Disadvantages
Cannot have a proper overview of the program/problem and
does not provide a good structure of a specific program
Lack of connections amongst the components
factorial(4) =
4 * factorial(3) =
4 * 3 * factorial(2) =
4 * 3 * 2 * factorial(1) =
4 * 3 * 2 * 1 = 24
char yes_or_no(void)
{
char answer = ‘X’;
while(answer != ‘y’ && answer != ‘n’)
{
printf (“Please enter ‘y’ or ‘n’:”);
scanf (“%c”, &answer);
}
return answer;
}
char yes_or_no(void)
{
char answer;
printf (“Please enter ‘y’ or ‘n’:”);
scanf (“%c”, &answer);
if(answer != ‘y’ && answer != ‘n’)
answer = yes_or_no( );
return answer;
}
1
2
3
A B C
© HĐC 2024.1 Chapter 3: Functions and Libraries 73
Towers of Hanoi
Let :
1 1
2 2 1
13 31 2
A B C
© HĐC 2024.1 Chapter 3: Functions and Libraries 74
Towers of Hanoi
#include <stdio.h>
is_path(maze, 7, 8)
x 7
y 8
0
1
2
3
4
5
6
7
8
9 F
0 1 2 3 4 5 6 7
is_path(maze, 7, 8)
x 7
y 7
is_path(maze, 7, 7)
0
1
2
3
4
5
6
7
8
9 F
0 1 2 3 4 5 6 7
is_path(maze, 7, 8)
x 7
y 9
is_path(maze, 7, 7)
0
1
2
3
is_path(maze, 7, 9) 4
5
6
7
8
9 F
0 1 2 3 4 5 6 7
Input/output: <stdio.h>
Character and string processing <string.h>, <ctype.h>
Mathematical operations <math.h>, <float.h>
Time, date <time.h>, <locale.h>
Dynamic memory allocation <stdlib.h>
Wide char funtions <wchar.h>, <wctype.h>
Other functions <assert.h>, <threads.h>, ...
https://www.cplusplus.com/reference/
https://devdocs.io/cpp/io/c
return 0;
}
int rand(void);
Return a random number within 0 and RAND_MAX
(inclusive)
RAND_MAX: 32767.
void srand( unsigned seed );
Seed value of an array created, usually start whenever rand is
called
char pet[5];
pet[0] = ‘l’; pet[1] = ‘a’; pet[2] = ‘m’; Equavalent
pet[3] = ‘b’; pet[4] = ‘\0’;
Cannot
Use = operator to assign a string to another string (strcpy
function in the library should be used instead)
Use == operator to compare 2 strings directly (strcmp function
in the library should be used instead)
Define a function in which a returning value is a string
Can
Input/output a string by using printf and scanf (the specifier is
%s)
#include <string.h>
...
char medium[ ] = “Four score and seven”;
char big[1000];
char small[5];
strcpy(big, medium);
strcpy(big, “Bob”);
strcpy(small, big);
strcpy(small, medium);
/* looks like trouble... */
small: Bob\0?
strcpy(str3, str1);
strcat(str3, str2);
/* strcat(s1, s2)
make a copy of s2 at the end of s1. */
str1 l a m b \0
str2 c h o p \0
str3 ? ? ? ? ? ? ? ? ? ? ?
str3 l a m b \0 ? ? ? ? ? ?
str3 l a m b c h o p \0 ? ?
char month[12][10] = {
“January”,
“February”,
...
“September”, /* longest month: 9 letters */
...
“December” };
...
printf(“%s is hot\n”, month[7]); /* August */
Source files
.c file: programs and functions in C
.h file: header files
Actual projects may contain hundreds *.c and *.h files
Compiled file (name and extension depend on systems)
Object files: files have been compiled and waiting for linking
Library files: set of functions have been pre-compiled
Executable files: machine code files have been linked and is
ready to be executed in computer memory
compiler compiler
ANSI lib
linker
other libs
.exe file
Defined in stdio.h
#define EOF (a certain negative value)
Usually -1
Input/output functions in the library use EOF to indicate the end
of file
Programs can also use EOF
Attention: EOF is the state, not an input value
printf(“File copied.\n”);
fclose(infilep);
fclose(outfilep);
void main() {
int k = max(5,7); // call (1)
double d = max(5.0,7.0); // call (2)
double a[] = {1,2,3,4,5,6};
d = max(d, a[1], a[2]); // call (3)
d = max(a, 5); // call (4)
d = max(5,7); // ?
d = max(d, 5); // ?
}
Advantages:
Useful as a normal function
As efficient as direct source code, not calling function
More reliable and safer than using Macro
Disadvantages:
If the function is called too many times in the program, the
source code will grow bigger (implementation code appears
multiple times in the program)
Function definition code must be open keep in header file
Create and use inline function when
Implementation code of the function is short (just a few line, no
loop)
Speed is the priority rather than memory capacity