Uploaded by NGỌC ÂN

TÀI LIỆU KỸ THUẬT LẬP TRÌNH

advertisement
TÀI LIỆU KỸ THUẬT LẬP TRÌNH
1. Mảng tĩnh với mảng động
• Mảng tĩnh
- Mãng tĩnh có kích thước cố định và được cấp phát trên Stack
- Kích thước của mảng tĩnh phải được xác định tại thời điểm biên dịch (trước khi chạy)
- Không cần xóa các mảng tỉnh vì chúng sẽ tự giải phóng sau khi vượt khỏi phạm vi
• Mảng động
- Mảng động được phân bổ trên Heap
- Kích thước của mảng động linh hoạt, có thể được xác định lúc biên dịch hoặc lúc chạy
- Có thể xây dựng các mảng động kích thước lớn trên Heap
- Cần phải giải phóng các mảng động bằng cách thủ công sau khi không còn dùng đến
2. So sánh mảng vs danh sách liên kết
Mảng
Danh sách được Liên kết
Mảng là một tập hợp các phần tử của một kiểu dữ Danh sách liên kết là một tập hợp có thứ tự của
liệu tương tự.
các phần tử cùng loại, trong đó mỗi phần tử được
kết nối với các con trỏ tiếp theo.
Các phần tử của mảng có thể được truy cập ngẫu Không thể truy cập ngẫu nhiên trong danh sách
nhiên bằng cách sử dụng chỉ mục mảng.
được liên kết. Các phần tử sẽ phải được truy cập
tuần tự.
Các phần tử dữ liệu được lưu trữ ở các vị trí liền Các phần tử mới có thể được lưu trữ ở bất cứ đâu
kề nhau trong bộ nhớ.
và một tham chiếu được tạo cho phần tử mới bằng
cách sử dụng con trỏ.
Các hoạt động Chèn và Xóa tốn kém hơn vì các vị Thao tác Chèn và Xóa nhanh chóng và dễ dàng
trí bộ nhớ liên tiếp và cố định.
trong danh sách được liên kết.
Bộ nhớ được cấp phát trong thời gian biên dịch Bộ nhớ được cấp phát trong thời gian chạy (Cấp
(Cấp phát bộ nhớ tĩnh).
phát bộ nhớ động).
Kích thước của mảng phải được chỉ định tại thời Kích thước của một danh sách được Liên kết tăng
điểm khai báo / khởi tạo mảng.
lên / thu nhỏ khi các phần tử mới được chèn / xóa.
Ưu điểm của danh sách được liên kết
Kích thước của danh sách liên kết không cố định, chúng có thể mở rộng và thu nhỏ trong thời gian chạy.
Thao tác Chèn và Xóa nhanh chóng và dễ dàng hơn trong Danh sách được Liên kết.
Việc cấp phát bộ nhớ được thực hiện trong thời gian chạy (không cần cấp phát bất kỳ bộ nhớ cố định nào).
Có thể dễ dàng triển khai các Cấu trúc dữ liệu như Ngăn xếp, Hàng đợi và cây bằng cách sử dụng Danh
sách được liên kết.
Nhược điểm của danh sách được liên kết
Tiêu thụ bộ nhớ nhiều hơn trong Danh sách được liên kết khi so sánh với mảng. Bởi vì mỗi nút chứa một
con trỏ trong danh sách liên kết và nó cần thêm bộ nhớ.
Các phần tử không thể được truy cập ngẫu nhiên trong danh sách được liên kết.
Không thể chuyển đổi từ ngược lại trong các danh sách được liên kết đơn lẻ.
3. Code chuẩn hóa chuỗi
int STRLEN(char *s)
{
int i = 0;
while(s[i] != '\0')
{
i++;
}
return i;
}
void XoaKyTu(char *s, int vitrixoa)
{
int length = STRLEN(s);
if(vitrixoa >= 0 && vitrixoa < length)
{
for(int i = vitrixoa + 1; i < length;
++i)
{
s[i - 1] = s[i];
}
s[length - 1] = '\0';
}
}
void XoaTatCaKhoangTrangODau(char *s)
{
int i = 0;
while(s[i] == ' ')
{
XoaKyTu(s, i--);
i++;
}
}
void XoaTatCaKhoangTrangOCuoi(char *s)
{
int length = STRLEN(s);
int i = length - 1;
while(s[i] == ' ')
{
XoaKyTu(s, i);
i--;
}
}
// Nguyên tắc: Gặp 2 khoảng trắng nằm cạnh
nhau thì xóa đi 1
void XoaKhoangTrangThuaGiua2Tu(char *s)
{
int length = STRLEN(s);
for(int i = 0; i < length - 1; ++i)
{
if(s[i] == ' ' && s[i + 1] == ' ')
{
XoaKyTu(s, i--);
length--;
}
}
}
void
VietHoaKyTuDauTienConLaiVietThuongCuaMoi
Tu(char *s)
{
int length = STRLEN(s);
if(s[0] >= 'a' && s[0] <= 'z')
{
s[0] -= 32;
}
for(int i = 1; i < length; ++i)
{
if(s[i] != ' ')
{
if(s[i - 1] == ' ') // có
nghĩa là s[i] là ký tự đầu tiên của từ
{
// Ký tự đầu tiên
phải là ký tự HOA => kiểm tra nếu hiện tại đang
là ký tự thường thì phải biến thành ký tự HOA
if(s[i] >= 'a' &&
s[i] <= 'z')
{
s[i] -=
32;
}
}
else // có nghĩa là s[i]
không phải là ký tự đầu tiên của từ
{
// Ký tự không
phải là đầu tiên phải là ký tự thường => kiểm tra
nếu hiện tại đang là ký tự HOA thì phải biến
thành ký tự thường
if(s[i] >= 'A' &&
s[i] <= 'Z')
{
s[i] +=
32;
}
}
}
}
}
char* ChuanHoaChuoi(char *s)
{
int length = STRLEN(s);
char *s1 = new char[length]
for(int i = 0; i <= length; ++i) // cho i chạy
đến length để sao chép luôn ký tự \0
{
s1[i] = s[i];
}
XoaTatCaKhoangTrangODau(s1);
XoaTatCaKhoangTrangOCuoi(s1);
XoaKhoangTrangThuaGiua2Tu(s1);
VietHoaKyTuDauTienConLaiVietThuong
CuaMoiTu(s1);
return s1;
}
4. Đọc File
ĐỌC TEXT CHUYỂN SANG NHỊ PHÂN VÀ ĐỌC NHỊ PHÂN CHUYỂN SANG TEXT
void convertTextToBinary(string text, string
int dong, cot;
binary)
//fscanf(FileIn_Text, "%d %d", &dong,
{
&cot);
/*FILE *FileIn_Text = fopen(text, "r");
FileIn_Text >> dong >> cot;
FILE *FileOut_Binary = fopen(binary,
"wb");*/ C
// sau khi đọc dữ liệu dòng cột từ tập tin
văn bản vào 2 biến trong chương trình thì đồng
ifstream FileIn_Text;
thời ghi 2 biến đó vào tập tin nhị phân luôn
FileIn_Text.open(text, ios_base::in);
//fwrite(&dong,
sizeof(dong),
1,
FileOut_Binary);
ofstream FileOut_Binary;
//fwrite(&cot,
sizeof(cot),
1,
//FileOut_Binary.open(binary,
FileOut_Binary);
ofstream::binary);
FileOut_Binary.write((char
*)&dong,
FileOut_Binary.open(binary,
sizeof(dong));
ios_base::out);
FileOut_Binary.write((char
*)&cot,
sizeof(cot));
if(!FileIn_Text)
{
for(int i = 0; i < dong; ++i)
// printf("\nKhong tim thay tap
{
tin %s", text);
for(int j = 0; j < cot; ++j)
cout << "\nKhong tim thay tap
{
tin " << text;
int x; // mỗi lần đọc dữ
//getch();
liệu từ tập tin văn bản vào biến x thì đồng thời
system("pause");
chúng ta ghi x ra tập tin nhị phân
return; // kết thúc hàm không
//fscanf(FileIn_Text,
làm nữa
"%d", &x);
}
//fwrite(&x, sizeof(x), 1,
FileOut_Binary);
FileIn_Text >> x;
FileOut_Binary.write((char
*)&x,
sizeof(x));
}
}
//printf("Du lieu tu tap tin van ban %s da
duoc ghi ra tap tin nhi phan %s", text, binary);
cout << "Du lieu tu tap tin van ban " <<
text << " da duoc ghi ra tap tin nhi phan " <<
binary;
//fread(&dong,
sizeof(dong),
1,
FileIn_Binary);
//fread(&cot,
sizeof(cot),
1,
FileIn_Binary);
FileIn_Binary.read((char
*)&dong,
sizeof(dong));
FileIn_Binary.read((char
*)&cot,
sizeof(cot));
//fprintf(FileOut_Text, "%hi %hi", dong,
cot);
FileOut_Text << dong << " " << cot;
//fclose(FileIn_Text);
//fclose(FileOut_Binary);
FileIn_Text.close();
FileOut_Binary.close();
}
// Hàm chuyển từ tập tin nhị phân sang text
// Đầu vào tập tin nhị phân, đầu ra tập tin text
void convertBinaryToText(string binary, string
text)
{
//FILE *FileOut_Text = fopen(text, "w");
//FILE *FileIn_Binary = fopen(binary,
"rb");
ofstream FileOut_Text;
FileOut_Text.open(text, ios_base::out);
ifstream FileIn_Binary;
//FileIn_Binary.open(binary,
ifstream::binary);
FileIn_Binary.open(binary, ios_base::in);
if(!FileIn_Binary)
{
//printf("\nKhong tim thay tap
tin %s", binary);
cout << "\nKhong tim thay tap
tin " << binary;
//getch();
system("pause");
return; // kết thúc hàm không
làm nữa
}
int dong, cot;
// sau khi đọc dữ liệu dòng cột từ tập tin
nhị phân vào 2 biến trong chương trình thì đồng
thời ghi 2 biến đó vào tập tin văn bản luôn
for(int i = 0; i < dong; ++i)
{
int x;
//fprintf(FileOut_Text, "\n");
FileOut_Text << "\n";
for(int j = 0; j < cot - 1; ++j)
{
// mỗi lần đọc dữ liệu
từ tập tin nhị phân vào biến x thì đồng thời chúng
ta ghi x ra tập tin văn bản
//fread(&x, sizeof(x), 1,
FileIn_Binary);
//fprintf(FileOut_Text,
"%d ", x);
FileIn_Binary.read((char
*)&x, sizeof(x));
FileOut_Text << x << " ";
}
//fread(&x,
sizeof(x),
1,
FileIn_Binary);
//fprintf(FileOut_Text, "%d", x);
FileIn_Binary.read((char *)&x,
sizeof(x));
FileOut_Text << x;
}
//printf("Du lieu tu tap tin nhi phan %s
da duoc ghi ra tap tin van ban %s", binary, text);
cout << "Du lieu tu tap tin nhi phan " <<
binary << " da duoc ghi ra tap tin van ban " <<
text;
//fclose(FileOut_Text);
//fclose(FileIn_Binary);
FileOut_Text.close();
FileIn_Binary.close();
}
ĐỌC TẬP TIN CÓ CẤU TRÚC VÀ THÊM VÀO DSLK
#include <iostream>
#include <fstream>
using namespace std;
struct Coordinate {
double x;
double y;
double r;
};
struct Circle {
Coordinate I;
};
struct Node {
Circle data;
Node* pNext;
};
struct List {
Node* pHead;
Node* pTail;
};
void initialize(List& l)
{
l.pHead = l.pTail = nullptr;
}
Node* createNode(Circle c)
{
Node* p = new Node;
if (p != nullptr)
{
p->data = c;
p->pNext = nullptr;
}
else
{
cout << "Allocate failed" << endl;
}
return p;
}
bool isEmpty(List& l)
{
Tự code;
}
void destroyList(List& l)
{
while (!isEmpty(l))
{
Node* temp = l.pHead;
l.pHead = temp->pNext;
delete temp;
}
}
void addTail(List& l, Circle c)
{
Node* p = createNode(c);
if (isEmpty(l))
{
l.pHead = l.pTail = p;
}
l.pHead->pNext = p;
l.pTail = p;
}
void readFileAndAddToList(ifstream& fin, List&
l)
{
Circle c;
while (!fin.eof())
{
fin >> c.I.x;
fin >> c.I.y;
fin >> c.I.r;
addTail(l, c);
}
}
double circumference(Coordinate c)
{
double circum = 2 * 3.14 * c.r;
return circum;
}
double area(Coordinate c)
{
double s = 3.14 * pow(c.r, 2);
return s;
}
void findMaxCircumference(ofstream& fout,
List l)
{
double max = 0;
Circle c;
for (Node* p = l.pHead; p != nullptr; p = p>pNext)
{
double temp = circumference(p->data.I);
if (temp > max)
{
temp = max;
c.I.x = p->data.I.x;
c.I.y = p->data.I.y;
c.I.r = p->data.I.r;
}
}
double a[50];
int i = 0;
for (Node* p = l.pHead; p != nullptr; p = p>pNext)
{
a[i] = area(p->data.I);
i++;
}
for (int j = i; j > 0; j--)
{
fout << a[j] << " ";
}
}
int main()
{
List l;
ifstream fin;
ofstream fout;
initialize(l);
fin.open("input.txt", ios_base::in);
readFileAndAddToList(fin, l);
fout.open("max.txt", ios_base::out);
findMaxCircumference(fout, l);
fout.close();
fout.open("area.txt", ios_base::out);
outputArea(fout, l);
fout.close();
destroyList(l);
fin.close();
fout << c.I.x << " " << c.I.y << " " << c.I.r <<
endl;
}
//ghi diện tích ra file txt
void outputArea(ofstream& fout, List l)
{
5. CÁC THAO TÁC DSLK ĐƠN
struct Node {
int data;
Node* pNext;
};
struct singlyLinkedList {
Node* pHead;
Node* pTail;
};
system("pause");
return 0;
}
void initialize(singlyLinkedList& l)
{
l.pHead = l.pTail = nullptr;
}
Node* createNode(int x)
{
Node* p = new Node;
if (p != nullptr)
{
p->data = x;
p->pNext = nullptr;
}
else
{
cout << "Allocate failed" <<
endl;
}
return p;
}
bool isEmpty(const singlyLinkedList& l)
{
if (l.pHead == nullptr)
{
return true;
}
return false;
}
void destroyList(singlyLinkedList& l)
{
while (!isEmpty(l))
{
Node* p = l.pHead;
l.pHead = p->pNext;
delete p;
}
}
void addHead(singlyLinkedList& l, int x)
{
Node* p = createNode(x);
if (isEmpty(l))
{
l.pHead = l.pTail = p;
}
else
{
p->pNext = l.pHead;
l.pHead = p;
}
}
void addTail(singlyLinkedList& l, int x)
{
Node* p = createNode(x);
if (l.pHead == nullptr)
{
l.pHead = l.pTail = p;
}
else
{
l.pTail->pNext = p;
l.pTail = p;
}
}
void removeHead(singlyLinkedList& l)
{
if (!isEmpty(l))
{
Node* p = l.pHead;
l.pHead = p->pNext;
delete p;
if (isEmpty(l))
{
l.pTail = nullptr;
}
}
else
{
cout<<"Nothing to do\n";
system("pause");
}
}
void removeTail(singlyLinkedList& l)
{
if (l.pHead->pNext == nullptr)
{
removeHead(l);
}
else
{
Node* p = l.pHead;
while (p->pNext->pNext !=
nullptr)
{
p = p->pNext;
}
delete(p->pNext);
p->pNext = nullptr;
}
}
void printList(singlyLinkedList l)
{
if (!isEmpty(l))
{
Node* p = l.pHead;
while (p != nullptr)
{
cout << p->data << " ";
p = p->pNext;
}
cout << endl;
}
else
{
cout << "List is empty" << endl;
}
}
void searchNotify(singlyLinkedList l, int x)
{
int order = searchOder(l, x);
Node* s = searchElement(l, x);
if (s != nullptr)
{
cout << "Node " << order << "
contain " << x << " value\n";
system("pause");
}
else
{
cout<<"Can't find "<< x <<" in
list\n";
system("pause");
}
}
Node* searchElement(singlyLinkedList l, int x)
{
Node* p = l.pHead;
while (p != nullptr && p->data != x)
{
p = p->pNext;
}
if (p != nullptr)
{
return p;
}
return nullptr;
}
void addYAfterX(singlyLinkedList& l,int x, int y)
{
Node* p = l.pHead;
while (p != nullptr && p->data != x)
{
p = p->pNext;
}
if (p != nullptr)
{
Node* temp = new Node;
temp->data = y;
temp->pNext = p->pNext;
p->pNext = temp;
}
else
{
cout<<"Oops! Can't find
"<<x<<" in the list\n";
}
}
int searchOrder(singlyLinkedList l, int x) (tìm vt)
{
int order = 0;
Node* p = l.pHead;
while (p != nullptr && p->data != x)
{
p = p->pNext;
order++;
}
if (p != nullptr)
{
return order;
}
return 0;
}
void deleteAfterX(singlyLinkedList& l, int x)
{
Node* p = l.pHead;
while (p != nullptr && p->data != x)
{
p = p->pNext;
}
if (p != nullptr)
{
{
Node* temp = p->pNext;
p->pNext = temp->pNext;
delete temp;
Node* cur = nullptr;
Node* pre = nullptr;
Node* p = l.pHead;
while (p != nullptr)
{
cur = p->pNext;
p->pNext = pre;
pre = p;
p = cur;
}
l.pHead = pre;
}
else
{
cout<<"Oops! Can't find "<< x
<<" in the list\n";
}
}
void reverse(singlyLinkedList& l)
}
NẾU QUẢN LÝ SV HAY SÁCH THÌ THÊM/THAY ĐỔI
void inputBookInfor(Book& book)
cout << "Enter price: ";
{
cin >> book.Price;
do
cout << "Enter stock: ";
{
cin >> book.Stocklevel;
cout << "Enter book title: ";
cin.ignore();
cin.ignore();
}
getline(cin, book.Title);
if (book.Title.length() > 200)
void inputList(singlyLinkedList& l) //Viết ở cuối
{
{
cout << "The book title
int n = 0, x;
max is 200 !" << endl;
do
}
{
} while (book.Title.length() > 200);
cout<<"Enter the number of
do
element: ";
{
cin >> n;
cout << "Enter book ISBN: ";
if (n <= 0)
getline(cin, book.ISBN);
{
if (book.ISBN.length() > 10)
cout<<"The number of
{
element must be more than 0 !\n ";
cout << "The book ID
}
max is 10 !" << endl;
} while (n <= 0);
}
} while (book.ISBN.length() > 10);
initialize(l);
do
for (int i = 0; i < n; i++)
{
{
cout << "Enter book author: ";
/*cout<<"Enter data node "<< i
getline(cin, book.Author);
+ 1 <<" : ";
if (book.Author.length() > 40)
cin >> x;
{
addTail(l, x);*/
cout << "The book
Book b;
author max is 40 !" << endl;
Cout<<"Enter book"<< i + 1
}
<<":"<< endl;
} while (book.Author.length() > 40);
Node* p = createNode(s);
addTail(p);
}
if (temp->data.ISBN ==
book.ISBN)
}
Node* createNode(Book& book)
{
inputBookInfor(book);
Node* p = new Node;
if (p != NULL)
{
p->data = book;
p->pNext = NULL;
}
else
{
cout << "Allocate failed" <<
endl;
}
return p;
}
void addHead(List& l, Book& book)
{
Node* p = createNode(book);
if (isEmpty(l))
{
l.pHead = l.pTail = p;
}
else
{
p->pNext = l.pHead;
l.pHead = p;
}
}
void addAndUpdateStock(List& l, Book& book)
{
Node* p = createNode(book);
if (isEmpty(l))
{
l.pHead = l.pTail = p;
}
else
{
int flag = 0;
Node* temp = l.pHead;
while (temp != NULL)
{
{
temp>data.Stocklevel += book.Stocklevel;
flag = 1;
}
temp = temp->pNext;
}
if (flag == 0)
{
l.pTail->pNext = p;
l.pTail = p;
}
}
}
void sellABook(List& l)
{
string s;
cout << "Enter ISBN: ";
cin >> s;
for (Node* p = l.pHead; p != NULL; p =
p->pNext)
{
if (p->data.ISBN == s)
{
if (p->data.Stocklevel >
0)
{
cout << "----Infor-----" << endl;
cout << "Name
of the book: " << p->data.Title << endl;
cout << "Price
of the book: " << p->data.Price << endl;
p>data.Stocklevel--;
}
else
{
cout << "Out of
stock" << endl;
}
}
}
}
{
void findBook(List l)
{
string s;
cin.ignore();
cout << "Enter book title: ";
getline(cin, s);
cout << "Search Result:" << endl;
cout << "\t--------------------" << endl;
for (Node* p = l.pHead; p != NULL; p =
p->pNext)
if (p->data.Title.find(s) <= p>data.Title.length())
{
cout << "Book ISBN: "
<< p->data.ISBN << endl;
cout << "Book title: " <<
p->data.Title << endl;
}
}
}
void removeBook(List& l, int k)
}
{
q = p;
Node* q = l.pHead;
}
for (Node* p = l.pHead->pNext; p !=
NULL; p = p->pNext)
if (!isEmpty(l))
{
{
while (p->data.Stocklevel < k)
if (l.pHead->data.Stocklevel < k)
{
{
Node* temp = p;
removeHead(l);
q->pNext = p->pNext;
}
p = q;
}
delete temp;
}
6. STACK, QUEUE
XỬ LÝ BIỂU THỨC HẬU TỐ
struct Node {
if (p!=nullptr)
int data;
{
Node* pNext;
p->data = x;
};
p->pNext = nullptr;
}
struct Stack {
else
Node* pTop;
{
};
cout << "Allocate failed\n";
}
void initialize(Stack& s)
return p;
{
}
s.pTop = nullptr;
}
void push(Stack& s, int x)
{
bool isEmpty(Stack& s)
Node* p = createNode(x);
{
if (isEmpty(s))
return(s.pTop == nullptr);
{
}
s.pTop = p;
}
Node* createNode(int x)
else
{
{
Node* p = new Node;
p->pNext = s.pTop;
s.pTop = p;
s.pTop = s.pTop->pNext;
delete p;
}
}
}
}
void pop(Stack& s, int& x)
{
if (!isEmpty(s))
{
Node* p = s.pTop;
x = p->data;
s.pTop = s.pTop->pNext;
delete p;
}
else
{
cout << "Stack is empty\n";
}
}
int top(Stack s)
{
if (!isEmpty(s))
{
return s.pTop->data;
}
else
return NULL;
}
void printStack(Stack s)
{
while (!isEmpty(s))
{
int x = 0;
pop(s, x);
cout << x << " ";
}
if (isEmpty(s))
{
cout << "Stack is empty\n";
}
}
void destroyStack(Stack& s)
{
while (!isEmpty(s))
{
Node* p = s.pTop;
int evaluatePostfix(Stack& s, char str[50])
{
int len = strlen(str);
for (int i = 0; i < len; i++)
{
if (str[i] == ' ')
{
continue;
}
else if (isdigit(str[i]))
{
push(s, str[i] - '0');
}
else
{
int x = 0, y = 0;
pop(s, y);
pop(s, x);
switch (str[i])
{
case'+':
push(s, x + y);
break;
case'-':
push(s, x - y);
break;
case'*':
push(s, x * y);
break;
case'/':
push(s, x / y);
break;
}
}
}
int result = 0;
pop(s, result);
return result;
}
void writeFile(FILE* fo, char str[], Stack s)
{
int result = evaluatePostfix(s, str);
cout << result << endl;
fopen_s(&fo, "result.txt", "wt");
if (fo != nullptr)
{
fprintf_s(fo, "%d", result);
cout << "The result of the postfix
expression has been output result.txt" << endl;
fclose(fo);
}
else
{
cout << "Can't open result.txt\n";
}
}
int main()
{
Stack s;
char str[50];
FILE* fi = nullptr;
FILE* fo = nullptr;
initialize(s);
fopen_s(&fi, "postfix.txt", "rt");
if (fi != nullptr)
{
fgets(str, 50, fi);
printf("%s\n", str);
writeFile(fo, str, s);
fclose(fi);
}
else
{
cout << "Can't open postfix.txt\n";
}
destroyStack(s);
system("pause");
return 0;
}
7. ĐỆ QUY
int sumOfEvenElement(int* a, int n)
{
if (n == 0)
{
return 0;
}
if (a[n - 1] % 2 == 0)
{
return sumOfEvenElement(a, n
- 1) + a[n - 1];
}
return sumOfEvenElement(a, n - 1);
}
bool checkPrime(int n, int i = 2)
{
if (n <= 2)
{
if (n == 2)
{
return true;
}
return false;
}
if (n % i == 0)
{
return false;
}
if(i*i > n)
{
return true;
}
return checkPrime(n, i + 1);
{
if (n == 1)
{
if (a[n - 1] > 0)
{
return a[n-1];
}
return -1;
}
int min = findMinPositiveElement(a, n-
}
int productOfPrimeElement(int* a, int n)
{
if (n < 1)
{
return 0;
}
if (n == 1)
{
return 1;
}
if (checkPrime(a[n - 1]))
{
return a[n 1]*productOfPrimeElement(a, n - 1);
}
return productOfPrimeElement(a, n 1);
}
bool checkNegative(int* a, int n)
{
if (n == 0)
{
return false;
}
if (n == 1)
{
if (a[n] < 0)
{
return true;
}
return false;
}
if (a[n - 1] >= 0)
{
return false;
}
return checkNegative(a, n - 1);
}
int findMinPositiveElement(int* a, int n)
1);
if (a[n-1] > 0)
{
if (a[n-1] < min)
{
min = a[n-1];
}
return min;
}
return min;
}
int countEqualX(int* a, int n, int x)
{
int count = 0;
if (n == -1)
{
return count;
}
if (a[n]!=x)
{
return countEqualX(a, n - 1, x);
}
return count + 1 + countEqualX(a, n - 1,
x);
}
int countDifferenceElement(int* a, int n)
{
if (n < 1)
{
return 0;
}
if (n == 1)
{
return 1;
}
int count = countDifferenceElement(a, n
- 1);
int flag = 1;
for (int i = 0; i <= n - 2; i++)
{
if (a[i] == a[n - 1])
{
flag = 0;
}
}
if (flag == 1)
count++;
return count;
}
8. MẢNG
void findElementInANotB(int* a, int* b, int na,
int nb) //function to find element which exist
in array a not b
{
int flag = 0;
for (int i = 0; i < na; i++)
{
flag = 1;
for (int j = 0; j < nb; j++)
{
if (a[i] == b[j])
{
flag = 0;
break;
}
}
if (flag == 1)
{
cout << a[i] << '\t';
}
}
cout << endl;
}
void deleteElement(int* a, int& n, int pos)
{
for (int i = pos; i < n; i++)
{
a[i] = a[i + 1];
}
n--;
}
void deleteDuplicate(int* a, int& n)
{
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] == a[j])
{
deleteElement(a, n, j);
j--;
}
}
}
}
void mergeTwoArray(int* a, int* b, int* &c, int
na, int nb) //function to join array a and array
b to array c without duplicate element
{
deleteDuplicate(a,na);
deleteDuplicate(b,nb);
int count = na;
for (int i = 0; i < na; i++)
{
c[i] = a[i];
}
for (int i = 0; i < nb; i++) {
int flag = 1;
for (int j = 0; flag == 1 && j < na; j++) {
if (a[j] == b[i]) {
flag = 0;
}
}
if (flag == 1) {
c[count] = b[i];
count++;
}
}
}
Mảng đường tròn
struct Circle
{
float x;
float y;
float r;
};
void inputCircle(Circle& p)
{
cout << "Enter coordinate x: ";
cin >> p.x;
cout << "Enter coordinate y: ";
cin >> p.y;
cout << "Enter radius r: ";
cin >> p.r;
}
void outputCircle(Circle p)
{
if (p.x > 0)
{
if(p.y > 0)
cout<< "(x - " << p.x <<
")^2 + (y - " << p.y << ")^2 = " << (p.r) * (p.r) <<
endl;
else if(p.y < 0)
cout<< "(x - " << p.x <<
")^2 + (y + " << -p.y << ")^2 = " << (p.r) * (p.r) <<
endl;
else
cout<< "(x - " << p.x <<
")^2 + (y)^2 = " << (p.r) * (p.r) << endl;
}
else if (p.x < 0)
{
if (p.y > 0)
cout << "(x + " << -p.x
<< ")^2 + (y - " << p.y << ")^2 = " << (p.r) * (p.r)
<< endl;
else if (p.y < 0)
cout << "(x + " << -p.x
<< ")^2 + (y + " << -p.y << ")^2 = " << (p.r) * (p.r)
<< endl;
else
cout << "(x+ " << -p.x <<
")^2 + (y)^2 = " << (p.r) * (p.r) << endl;
}
else
{
if (p.y > 0)
cout << "(x)^2 + (y - " <<
p.y << ")^2 = " << (p.r) * (p.r) << endl;
else if (p.y < 0)
cout << "(x)^2 + (y + "
<< -p.y << ")^2 = " << (p.r) * (p.r) << endl;
else
cout << "(x)^2 + (y)^2 =
" << (p.r) * (p.r) << endl;
}
}
//funtion to calculate circumference
void calCircum(Circle p)
{
float c = 0;
c = 2 * p.r * 3.14;
cout << c << endl;
}
//function to calculate area
float calArea(Circle p)
{
float a = 0;
a = 3.14 * p.r * p.r;
return a;
}
void inputCircleArray(Circle* arr, int& n)
{
for (int i = 0; i < n; i++)
{
cout << "Enter element a[" << i
<< "]:\n";
inputCircle(arr[i]);
}
}
void outputCircleArray(Circle* arr, int n)
{
for (int i = 0; i < n; i++)
{
outputCircle(arr[i]);
}
}
//function to sort array increase by area of
circle element
void sortArrayIncrease(Circle*& arr, int n)
{
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (calArea(arr[i]) >
{
calArea(arr[j]))
if (checkIntersect(arr[i],
{
arr[j]) == 1)
Circle temp =
{
arr[i];
arr[i] = arr[j];
arr[j] = temp;
outputCircle(arr[i]);
}
outputCircle(arr[j]);
}
cout << endl;
}
}
}
}
}
//function to calculate distance between two
point
float distanceBwTwoPoint(Circle a, Circle b)
{
return sqrt(pow((b.x - a.x), 2) + pow((b.y
- a.y), 2));
}
}
//function to check two circle intersect
int checkIntersect(Circle a, Circle b)
{
int check = 0;
float r1 = a.r + b.r;
float r2 = 0;
if (a.r >= b.r)
{
r2 = a.r - b.r;
}
else
{
r2 = b.r - a.r;
}
float d = distanceBwTwoPoint(a, b);
if (d > r2 && d < r1)
{
check = 1;
}
return check;
}
void inputFraction(fraction& fr)
{
cout << "Enter numerator: ";
cin >> fr.num;
do
{
cout << "Enter denominatior: ";
cin >> fr.den;
if (fr.den == 0)
{
cout << "The denominator must be larger
than 0. Enter new value." << endl;
}
}
while(fr.den == 0);
}
//function to list circle pair which intersect
void listCirclePair(Circle* arr, int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
//function to find greatest common divisor
float findGCD(float a, float b)
{
if (a < 0)
{
a = a * -1;
MẢNG PHÂN SỐ
struct fraction {
float num; //num is numerator
float den; //den is denominator
};
void outputFraction(fraction fr)
{
cout << fr.num << "/" << fr.den << endl;
}
}
if (b < 0)
{
b = b * -1;
}
if (a == 0 && b != 0)
{
return b;
}
while (a != b)
{
if (a > b)
{
a = a - b;
}
else
b = b - a;
}
return a;
return simplify(ans);
}
//function to multiply two fractions
fraction multiply(fraction f1, fraction f2)
{
fraction ans;
ans.num = f1.num * f2.num;
ans.den = f1.den * f2.den;
return simplify(ans);
}
//function to divide two fractions
fraction divide(fraction f1, fraction f2)
{
fraction ans;
ans.num = f1.num * f2.den;
ans.den = f1.den * f2.num;
return simplify(ans);
}
}
//function to simplify fraction
fraction simplify(fraction fr)
{
float x = findGCD(fr.num, fr.den);
fr.num = fr.num / x;
fr.den = fr.den / x;
return fr;
}
//function to add two fractions
fraction add(fraction f1, fraction f2)
{
fraction ans;
ans.num = f1.num * f2.den + f1.den *
f2.num;
ans.den = f1.den * f2.den;
return simplify(ans);
}
//function to subtract two fractions
fraction subtract(fraction f1, fraction f2)
{
fraction ans;
ans.num = f1.num * f2.den - f1.den *
f2.num;
ans.den = f1.den * f2.den;
//function to compare two fractions
int compare(fraction f1, fraction f2)
{
float a = f1.num / f1.den;
float b = f2.num / f2.den;
if (a > b)
{
return 1;
}
else if (a < b)
{
return -1;
}
else
{
return 0;
}
}
void inputArrayFraction(fraction* arr, int n)
{
for (int i = 0; i < n; i++)
{
cout << "Enter element a[" << i
<< "]:\n";
inputFraction(arr[i]);
}
}
}
void ouputArrayFraction(fraction* arr, int n)
{
for (int i = 0; i < n; i++)
{
outputFraction(arr[i]);
}
}
//function to check fraction in array and return
value 1 or 0
int checkFractionInArray(fraction* arr, int n,
fraction k)
{
for (int i = 0; i < n; i++)
{
if (compare(arr[i],k)==0)
{
return 1;
}
}
return 0;
}
//function to calculate all fraction element in
array
fraction addFractionArray(fraction* arr, int n)
{
fraction sum = arr[0];
for (int i = 1; i < n; i++)
{
sum = add(sum, arr[i]);
}
return sum;
}
//function to simplify fraction in array
void simplifyFractionArray(fraction*& arr, int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = simplify(arr[i]);
}
}
//function to sort array increase
void sortIncrease(fraction* arr, int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if
(compare(arr[i],arr[j])==1)
{
fraction temp =
arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
MẢNG MA TRẬN
void CapPhatKhoiTaoMang(int **&a, int &row,
int &col)
{
do
{
cout << "Enter the number of
row in matrix: ";
cin >> row;
cout << "Enter the number of
collum in matrix: ";
cin >> col;
if (row <= 0 || col <= 0)
{
cout << "The number of
row and collum must be more than 0" << endl;
}
} while (row <= 0 || col <= 0);
matrix = new int* [row];
for (int i = 0; i < row; i++)
{
matrix[i] = new int[col];
}
//function to find max value at the edge of
matrix
void findMaxValueAtEdge(int** a, int r, int c)
{
int max = 0;
int max1 = a[0][0];
int max2 = a[0][0];
for (int j = 0; j < c; j++)
{
if (a[0][j] > max1 && (a[r - 1][j])
< a[0][j])
{
max1 = a[0][j];
}
if (a[r - 1][j] > max1 && a[r 1][j] > a[0][j])
{
max1 = a[r - 1][j];
}
}
for (int i = 0; i < r; i++)
{
if (a[i][0] > max2 && a[i][0] >
a[i][c - 1])
{
max2 = a[i][0];
}
if (a[i][c - 1] > max2 && a[i][c 1] > a[i][0])
{
max2 = a[i][c - 1];
}
}
if (max1 > max2)
{
max = max1;
}
else
{
max = max2;
}
cout << max << endl;
}
//function to list line contain at least one
negative value
void listLine1(int** a, int r, int c)
{
int check = 0;
for (int i = 0; i < r; i++)
{
check = -1;
for (int j = 0; j < c; j++)
{
if (a[i][j] < 0)
{
check = 1;
break;
}
}
if (check == 1)
{
cout <<"Line "<< i << "
";
}
}
cout << endl;
}
//function to list line contain all even number
void listLine2(int** a, int r, int c)
{
int count = 0;
for (int i = 0; i < r; i++)
{
count = 1;
for (int j = 0; j < c; j++)
{
if (a[i][j] % 2 != 0)
{
count = -1;
break;
}
}
if (count == 1)
cout << "Line "<< i << "
";
}
cout << endl;
}
//function to find min value in row (support to
find saddle point function)
bool findMinValueInRow(int** a, int pr, int pc,
int c)
{
int min = a[pr][pc];
for (int i = 0; i < c; i++)
{
if (a[pr][i] < min)
{
return false;
}
}
return true;
}
}
cout << count << endl;
}
}
//function to find max value in collum (support
to find saddle point function)
bool findMaxValueInCollum(int** a, int pr, int
pc, int r)
{
int max = a[pr][pc];
for (int i = 0; i < r; i++)
{
if (a[i][pc] > max)
{
return false;
}
}
return true;
}
9. BONUS
bool checkSame(int* a, int n, int index)
//function to check same element in array
{
for (int i = index - 1; i >= 0; i--)
{
if (a[i] == a[index])
{
return true;
}
}
return false;
}
int countPrimeNumNotSame(int* a, int n)
//function to count the number of prime
number which have difference value
{
int count = 0;
for (int i = 0; i < n; i++)
{
if (checkSame(a, n, i) == false)
{
if (checkPrimeNum(a[i]) == true)
{
count++;
}
}
}
return count;
}
//function to count the number of saddle point
in matrix
void countSaddlePointElement(int** a, int r, int
c)
{
int count = 0;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
if
(findMinValueInRow(a, i, j, c)==true &&
findMaxValueInCollum(a, i, j, r)==true)
{
count++;
}
Đệ quy trong C++ là quá trình trong đó một phương thức gọi lại chính nó một cách liên tiếp.
Cấp phát bộ nhớ động (Dynamic memory allocation) là cách để yêu cầu bộ nhớ từ hệ điều hành khi
cần thiết (thời điểm chương trình đang chạy). Cấp phát bộ nhớ động sử dụng vùng nhớ được quản lý bởi
hệ điều hành được gọi là heap. Như vậy ta không cần khai báo trước kích thước tối đa của mảng, mà kích
thước tối đa của mảng có thể được tính toán cho phù hợp sau đó, tại thời điểm chạy chương trình.
void XuatHe2(long n)
cout << n%2;
{
}
if(n == 0)
return; // kết thúc hàm
void XuatHe8(long n)
{
XuatHe2(n / 2); // 2: Bước lặp
if(n == 0)
return; // kết thúc hàm
XuatHe8(n / 8); // 2: Bước lặp
cout << n%8;
}
void XuatHe16(long n)
{
// 1: Điều kiện dừng
if(n == 0)
return; // kết thúc hàm
XuatHe16(n / 16); // 2: Bước lặp
int x = n % 16;
if(x < 10)
printf("%d", x);
else if(x == 10)
printf("A");
else if(x == 11)
printf("B");
else if(x == 12)
printf("C");
else if(x == 13)
printf("D");
else if(x == 14)
printf("E");
else if(x == 15)
printf("F");
}
Download