tài liệu C++(4)

- 0 / 0
(Tài liệu chưa được thẩm định)
Nguồn:
Người gửi: Lê Văn Thuận (trang riêng)
Ngày gửi: 00h:20' 09-04-2024
Dung lượng: 632.8 KB
Số lượt tải: 43
Nguồn:
Người gửi: Lê Văn Thuận (trang riêng)
Ngày gửi: 00h:20' 09-04-2024
Dung lượng: 632.8 KB
Số lượt tải: 43
Số lượt thích:
0 người
.c
om
ng
co
th
an
Ngôn ngữ lập trình C++
cu
u
du
o
ng
Chương 4 – Mảng
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
u
du
o
ng
th
an
co
ng
Giới thiệu
Mảng
Khai báo mảng
Ví dụ về sử dụng mảng
Truyền tham số cho hàm
Sắp xếp mảng
Ví dụ: Dùng mảng tính Mean, Median và Mode
Tìm kiếm trên mảng: Tìm kiếm Tuyến tính và tìm kiếm Nhị phân
Mảng nhiều chiều
cu
Đề mục
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.9
.c
om
Chương 4 – Mảng
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Giới thiệu
4.1
.c
om
• Mảng (array)
co
ng
– Cấu trúc của những phần tử dữ liệu có liên quan
– Thực thể tĩnh (giữ nguyên kích thước trong suốt chương
trình)
an
• Một vài loại mảng
cu
u
du
o
ng
th
– mảng dựa vào con trỏ (Pointer-based arrays) (C-like)
– mảng là đối tượng (Arrays as objects) (C++)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Mảng
4.2
.c
om
• Mảng
co
• Truy nhập đến 1 phần tử
ng
– Tập hợp các vùng nhớ liên tiếp
– Cùng tên, cùng kiểu (int, char, ...)
ng
th
an
– Chỉ ra tên mảng và vị trí - position (chỉ số - index)
– Cú pháp: tên_mảng[ chỉ_số ]
du
o
– Phần tử đầu tiên ở vị trí 0
• Mảng c có n phần tử
cu
u
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Phần tử thứ N ở vị trí thứ N-1
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Mảng
4.2
.c
om
• Phần tử của mảng cũng như các biến khác
– Gán giá trị và in mảng số nguyên c
co
ng
c[ 0 ] = 3;
cout << c[ 0 ];
an
• Có thể sử dụng các phép toán trong cặp ngoặc vuông
cu
u
du
o
ng
th
c[ 5 – 2 ] cũng giống c[3]
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
c[1]
6
c[2]
0
72
an
c[3]
1543
-89
c[6]
0
c[7]
62
c[8]
-3
c[9]
1
c[10]
6453
c[11]
78
cu
u
du
o
c[5]
ng
th
c[4]
ng
-45
co
c[0]
.c
om
Tên mảng
(Lưu ý rằng mọi phần tử
của mảng này đều có cùng
tên, c)
Chỉ số của phần tử
trong mảng c
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
4.3
Khai báo mảng
co
• Bất cứ kiểu dữ liệu nào
ng
– Tên
– Kiểu của mảng
.c
om
• Khi khai báo mảng, chỉ rõ
th
an
– Số phần tử
– type arrayName[ arraySize ];
du
o
ng
int c[ 10 ]; // mảng của 10 số nguyên
float d[ 3284 ]; // mảng của 3284 số thực
• Khai báo nhiều mảng cùng kiểu
cu
u
– Sử dụng dấu phẩy như với các biến bình thường
int b[ 100 ], x[ 27 ];
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Khởi tạo mảng
ng
– Dùng vòng lặp khởi tạo từng phần tử
– Khởi tạo cả danh sách
.c
om
Ví dụ về sử dụng mảng
4.4
co
• Chỉ rõ từng phần tử khi khai báo mảng
int n[ 5 ] = { 1, 2, 3, 4, 5 };
ng
th
an
• Nếu trong danh sách không có đủ số giá trị khởi tạo, các phần tử ở
bên phải nhất sẽ nhận giá trị 0
• Nếu danh sách thừa sẽ gây lỗi cú pháp
du
o
– Khởi tạo giá trị bằng 0 cho tất cả các phần tử
int n[ 5 ] = { 0 };
cu
u
– Nếu không khai báo kích thước mảng, kích thước của danh sách
các giá trị khởi tạo sẽ quyết định kích thước mảng
int n[] = { 1, 2, 3, 4, 5 };
• Có 5 giá trị khởi tạo, do đó mảng có 5 phần tử
• Nếu không khai báo kích thước mảng thì phải khởi tạo khi khai báo
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.3: fig04_03.cpp
// Initializing an array.
#include
fig04_03.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
ng
#include
using std::setw;
co
an
th
Khởi tạo mảng bằng vòng lặp for.
// n is an array of 10 integers
ng
int main()
{
int n[ 10 ];
Khai báo mảng 10 phần tử số nguyên.
Chú ý rằng mảng gồm các phẩn tử
từ n[0] đến n[9].
u
du
o
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
n[ i ] = 0;
// set element at location i to 0
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array n in tabular format
for ( int j = 0; j < 10; j++ )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
26
27
28
return 0;
// indicates successful termination
} // end main
u
du
o
ng
th
an
co
ng
Value
0
0
0
0
0
0
0
0
0
0
cu
Element
0
1
2
3
4
5
6
7
8
9
.c
om
fig04_03.cpp
(2 of 2)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_03.cpp
output (1 of 1)
// Fig. 4.4: fig04_04.cpp
// Initializing an array with a declaration.
#include
fig04_04.cpp
(1 of 1)
.c
om
using std::cout;
using std::endl;
ng
#include
using std::setw;
co
Lưu ý cách dùng danh sách
khởi tạo cho mảng.
du
o
ng
th
an
int main()
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
cout << "Element" << setw( 13 ) << "Value" << endl;
u
// output contents of array n in tabular format
for ( int i = 0; i < 10; i++ )
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
return 0;
// indicates successful termination
} // end main
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Value
32
27
64
18
95
14
90
70
60
37
u
du
o
ng
th
an
co
ng
.c
om
fig04_04.cpp
output (1 of 1)
cu
Element
0
1
2
3
4
5
6
7
8
9
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Kích thước của mảng
.c
om
Ví dụ về sử dụng mảng
4.4
– Có thể được xác định bằng hằng số (const)
ng
• const int size = 20;
cu
u
du
o
ng
th
an
co
– Hằng số không thể thay đổi
– Hằng phải được khởi tạo khi khai báo
– Còn được gọi là “named constant” (giá trị được đặt tên) hoặc
“read-only variable” (biến chỉ đọc)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.5: fig04_05.cpp
// Initialize array s to the even integers from 2 to 20.
#include
fig04_05.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
ng
#include
Chú ý từ khoá const. Chỉ có
các biến const được dùng
để khai
báo kích
thướcsize
mảng.
to
specify
array
int s[ arraySize ];
du
o
ng
th
an
int main()
{
// constant variable can be used
const int arraySize = 10;
co
using std::setw;
// array s has 10 elements
u
Chương trình dễ thay đổi hơn khi ta
dùng hằng (const) cho kích thước của
for ( int i = 0; i < arraySize; i++ ) // set the values
mảng.
s[ i ] = 2 + 2 * i;
Ta có thể thay đổi arraySize, và tất
cả các vòng lặp vẫn hoạt động bình
cout << "Element" << setw( 13 ) << "Value" << endl;
thường (nếu không, ta phải sửa mọi
vòng lặp trong chương trình).
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// output contents of array s in tabular format
for ( int j = 0; j < arraySize; j++ )
cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
// indicates successful termination
.c
om
return 0;
co
an
th
ng
du
o
u
Value
2
4
6
8
10
12
14
16
18
20
ng
} // end main
Element
0
1
2
3
4
5
6
7
8
9
fig04_05.cpp
(2 of 2)
cu
24
25
26
27
28
29
30
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_05.cpp
output (1 of 1)
// Fig. 4.6: fig04_06.cpp
// Using a properly initialized constant variable.
#include
fig04_06.cpp
(1 of 1)
.c
om
using std::cout;
using std::endl;
// initialized constant variable
co
int main()
{
const int x = 7;
ng
Khởi tạo hằng
th
an
cout << "The value of constant variable x is: "
<< x << endl;
} // end main
ng
// indicates successful termination
du
o
return 0;
cu
u
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
The value of constant variable x is: 7
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_06.cpp
output (1 of 1)
// Fig. 4.7: fig04_07.cpp
// A const object must be initialized.
Lỗi cú pháp do không khởi tạo hằng.
Sửa giá trị của hằng cũng là một lỗi.
fig04_07.cpp
(1 of 1)
// Error: x must be initialized
.c
om
int main()
{
const int x;
// Error: cannot modify a const variable
return 0;
// indicates successful termination
co
ng
x = 7;
an
} // end main
ng
th
1
2
3
4
5
6
7
8
9
10
11
12
cu
u
du
o
d:\cpphtp4_examples\ch04\Fig04_07.cpp(6) : error C2734: 'x' :
const object must be initialized if not extern
d:\cpphtp4_examples\ch04\Fig04_07.cpp(8) : error C2166:
l-value specifies const object
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_07.cpp
output (1 of 1)
// Fig. 4.8: fig04_08.cpp
// Compute the sum of the elements of the array.
#include
fig04_08.cpp
(1 of 1)
.c
om
using std::cout;
using std::endl;
co
ng
int main()
{
const int arraySize = 10;
th
an
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ng
int total = 0;
u
du
o
// sum contents of array a
for ( int i = 0; i < arraySize; i++ )
total += a[ i ];
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cout << "Total of array element values is " << total << endl;
return 0;
} // end main
// indicates successful termination
Total of array element values is 55
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_08.cpp
output (1 of 1)
.c
om
Value
19
3
15
7
11
9
13
5
17
1
ng
co
du
o
ng
th
an
// Fig. 4.9: fig04_09.cpp
// Histogram printing program.
Element
#include
0
1
using std::cout;
2
using std::endl;
3
4
#include
5
6
using std::setw;
7
8
int main()
9
{
Histogram
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
u
const int arraySize = 10;
int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fig04_09.cpp
(1 of 2)
cout << "Element" << setw( 13 ) << "Value"
<< setw( 17 ) << "Histogram" << endl;
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// for each element of array n, output a bar in histogram
for ( int i = 0; i < arraySize; i++ ) {
cout << setw( 7 ) << i << setw( 13 )
In số dấu saofig04_09.cpp
(*) tương ứng
<< n[ i ] << setw( 9 );
với giá trị của
(2 phần
of 2) tử n[i].
ng
// start next line of output
co
cout << endl;
CuuDuongThanCong.com
Value
19
3
15
7
11
9
13
5
17
1
ng
du
o
Element
0
1
2
3
4
5
6
7
8
9
th
// indicates successful termination
u
} // end main
an
} // end outer for structure
return 0;
// print one bar
.c
om
for ( int j = 0; j < n[ i ]; j++ )
cout << '*';
cu
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Histogram
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
https://fb.com/tailieudientucntt
fig04_09.cpp
output (1 of 1)
// Fig. 4.10: fig04_10.cpp
// Roll a six-sided die 6000 times.
#include
fig04_10.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
#include
ng
Viết lại một chương trình cũ. Một
mảng được sử dụng thay cho 6
biến thường, và các phần tử dễ
dàng cập nhật hơn (không cần sử
dụng switch).
co
using std::setw;
th
an
#include
#include
du
o
ng
int main()
{
const int arraySize = 7;
int frequency[ arraySize ] = { 0 };
Dòng lệnh này tạo ra một số trong
khoảng 1 đến 6 và tăng phần tử
// seed random-number generator
frequency[] có chỉ số đó.
u
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
srand( time( 0 ) );
// roll die 6000 times
for ( int roll = 1; roll <= 6000; roll++ )
++frequency[ 1 + rand() % 6 ]; // replaces 20-line switch
// of Fig. 3.8
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
cout << "Face" << setw( 13 ) << "Frequency" << endl;
ng
// indicates successful termination
co
return 0;
.c
om
// output frequency elements 1-6 in tabular format
for ( int face = 1; face < arraySize; face++ )
cout << setw( 4 ) << face
<< setw( 13 ) << frequency[ face ] << endl;
} // end main
ng
du
o
u
Frequency
1003
1004
999
980
1013
1001
cu
Face
1
2
3
4
5
6
th
an
26
27
28
29
30
31
32
33
34
35
36
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_10.cpp
(2 of 2)
fig04_10.cpp
output (1 of 1)
// Fig. 4.11: fig04_11.cpp
***modified***
// Student mark statistic program.
#include
fig04_11.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
ng
#include
co
using std::setw;
du
o
ng
th
an
int main()
{
// define array sizes
const int markSize = 40;
// size of array of marks
const int frequencySize = 11; // size of array frequency
u
// place student marks in array of marks
int marks[ markSize ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8,
10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7,
5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// initialize frequency counters to 0
int frequency[ frequencySize ] = { 0 };
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
.c
om
// for each student's mark, select value of an element of array
// responses and use that value as subscript in array
// frequency to determine element to increment
fig04_11.cpp
for ( int student = 0; student < markSize; student++ )
(2 of 2)
++frequency[ marks[student] ];
ng
// display results
cout << "Rating" << setw( 17 ) << "Frequency" << endl;
th
an
co
// output frequencies in tabular format
for ( int rating = 1; rating < frequencySize; rating++ )
cout << setw( 6 ) << rating
<< setw( 17 ) << frequency[ rating ] << endl;
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
ng
Rating
1
2
3
4
5
6
7
8
9
10
du
o
} // end main
// indicates successful termination
marks[student] là điểm (từ 1 đến 10).
Giá trị này quyết định chỉ số của phần tử
frequency[] cần tăng.
u
return 0;
cu
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Frequency
2
2
2
2
5
11
5
7
1
3
Ví dụ về sử dụng mảng
4.4
.c
om
• Xâu - string (xem thêm ở chương 5)
ng
– Mảng của các ký tự
– Mọi xâu đều kết thúc với ký tự null ('\0')
co
– Ví dụ
an
• char string1[] = "hello";
th
– Ký tự null tự động được thêm vào, xâu có 6 phần tử
du
o
ng
• char string1[] = { 'h', 'e', 'l', 'l',
'o', '\0' };
– Chỉ số cũng giống như đối với mảng
cu
u
String1[ 0 ] bằng 'h'
string1[ 2 ] bằng 'l'
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Nhập từ bàn phím bằng cin
ng
char string2[ 10 ];
cin >> string2;
.c
om
Ví dụ về sử dụng mảng
4.4
co
– Ghi dữ liệu vào của người dùng vào xâu
th
an
• Dừng lại ở ký tự trắng đầu tiên (tab, newline, blank…)
• Thêm vào ký tự null
ng
– Nếu nhập quá nhiều, dữ liệu sẽ tràn mảng
u
cu
• In xâu
du
o
• Ta cần phải tránh điều này (mục 5.12 sẽ giải thích phương
pháp)
– cout << string2 << endl;
• Không sử dụng được với các mảng có kiểu dữ liệu khác
– In các ký tự cho đến khi gặp null
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4_12: fig04_12.cpp
// Treating character arrays as strings.
#include
fig04_12.cpp
(1 of 2)
.c
om
using std::cout;
using std::cin;
using std::endl;
Hai cách khác nhau để khai báo
xâu. string2 được khởi tạo và
kích thước được xác định tự động.
th
an
co
ng
int main()
{
char string1[ 20 ],
// reserves 20 characters
char string2[] = "string literal"; // reserves 15 characters
Ví dụ về đọc xâu từ bàn phím và in ra.
du
o
ng
// read string from user into array string2
cout << "Enter the string \"hello there\": ";
cin >> string1; // reads "hello" [space terminates input]
u
// output strings
cout << "string1 is: " << string1
<< "\nstring2 is: " << string2;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
cout << "\nstring1 with spaces between characters is:\n";
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// output characters until null character is reached
for ( int i = 0; string1[ i ] != '\0'; i++ )
cout << string1[ i ] << ' ';
ng
.c
om
Có thể truy nhập xâu
giống
fig04_12.cpp
như đối với mảng. Vòng
(2 of lặp
2)
cin >> string1; // reads "there"
kết thúc khi gặp ký tự null.
cout << "\nstring1 is: " << string1 << endl;
fig04_12.cpp
output (1 of 1)
return 0; // indicates successful termination
} // end main
an
co
24
25
26
27
28
29
30
31
32
33
cu
u
du
o
ng
th
Enter the string "hello there": hello there
string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
h e l l o
string1 is: there
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Ví dụ về sử dụng mảng
4.4
.c
om
• Kiểu lưu trữ tĩnh – static storage (chương 3)
an
co
ng
– Nếu là static, các biến địa phương lưu lại giá trị giữa các
lần gọi hàm
– chỉ được nhìn thấy trong thân hàm
– Có thể khai báo mảng địa phương là static
ng
th
• được khởi tạo về 0
static int array[3];
du
o
• Nếu không phải static
cu
u
– Được tạo (và huỷ) tại mỗi lần gọi hàm
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.13: fig04_13.cpp
// Static arrays are initialized to zero.
#include
fig04_13.cpp
(1 of 3)
ng
// function prototype
// function prototype
co
void staticArrayInit( void );
void automaticArrayInit( void );
.c
om
using std::cout;
using std::endl;
du
o
ng
th
an
int main()
{
cout << "First call to each function:\n";
staticArrayInit();
automaticArrayInit();
u
cout << "\n\nSecond call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << endl;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
return 0;
// indicates successful termination
} // end main
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_13.cpp
(2 of 3)
.c
om
// function to demonstrate a static local array
void staticArrayInit( void )
Mảng static, khởi tạo về 0 tại
{
lần gọi hàm đầu tiên.
// initializes elements to 0 first time function is called
static int array1[ 3 ];
cout << "\nValues on entering staticArrayInit:\n";
an
co
ng
// output contents of array1
for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = " << array1[ i ] << "
th
cout << "\nValues on exiting staticArrayInit:\n";
ng
contents of array1
3; j++ )
<< j << "] = "
j ] += 5 ) << " ";
Dữ liệu trong mảng bị thay đổi,
các thay đổi được bảo toàn.
u
du
o
// modify and output
for ( int j = 0; j <
cout << "array1["
<< ( array1[
";
cu
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
} // end function staticArrayInit
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
.c
om
// function to demonstrate an automatic local array
void automaticArrayInit( void )
Mảng automatic, được tạo lại
{
tại mỗi lần gọi hàm.
fig04_13.cpp
// initializes elements each time function is called
(3 of 3)
int array2[ 3 ] = { 1, 2, 3 };
cout << "\n\nValues on entering automaticArrayInit:\n";
an
co
ng
// output contents of array2
for ( int i = 0; i < 3; i++ )
cout << "array2[" << i << "] = " << array2[ i ] << "
";
th
cout << "\nValues on exiting automaticArrayInit:\n";
ng
contents of array2
3; j++ )
<< j << "] = "
j ] += 5 ) << " ";
u
du
o
// modify and output
for ( int j = 0; j <
cout << "array2["
<< ( array2[
Tuy mảng bị thay đổi, nó sẽ bị
huỷ khi hàm kết thúc và thayt
đổi trong dữ liệu sẽ bị mất.
cu
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
} // end function automaticArrayInit
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
First call to each function:
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
.c
om
Values on
array2[0]
Values on
array2[0]
fig04_13.cpp
output (1 of 1)
ng
entering staticArrayInit:
= 0 array1[1] = 0 array1[2] = 0
exiting staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
an
co
Values on
array1[0]
Values on
array1[0]
th
Second call to each function:
entering staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
exiting staticArrayInit:
= 10 array1[1] = 10 array1[2] = 10
Values on
array2[0]
Values on
array2[0]
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
cu
u
du
o
ng
Values on
array1[0]
Values on
array1[0]
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Truyền tham số cho hàm
4.5
.c
om
• Dùng tên mảng, bỏ cặp ngoặc vuông
– Truyền mảng myArray cho hàm myFunction
ng
int myArray[ 24 ];
myFunction( myArray, 24 );
co
– Kích thước mảng thường được truyền, nhưng không nhất thiết
an
• Có ích khi dùng để duyệt tất cả các phần tử
th
• Mảng được truyền bằng tham chiếu (passed-by-reference)
du
o
ng
– Hàm có thể thay đổi dữ liệu gốc của mảng
– Tên mảng có giá trị bằng địa chỉ của phần tử đầu tiên
u
• Hàm biết mảng được lưu ở đâu.
• Hàm có thể sửa đổi dữ liệu ghi trong mảng
cu
• Các phần tử mảng được truyền bằng giá trị (passed-byvalue)
– Như các biến thông thường
– square( myArray[3] );
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Truyền tham số cho hàm
4.5
.c
om
• Các hàm dùng mảng làm đối số
– Function prototype
co
ng
• void modifyArray( int b[], int arraySize );
• void modifyArray( int [], int );
an
– Trong prototype, tên không bắt buộc
th
• cả hai hàm lấy đối số là một mảng số nguyên và 1 số nguyên
ng
– Không ghi cần kích thước mảng trong cặp ngoặc
du
o
• Trình biên dịch bỏ qua
– Nếu khai báo 1 tham số là const
cu
u
• đối số đó sẽ không thể bị thay đổi (chương trình dịch báo lỗi)
• void doNotModify( const int [] );
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.14: fig04_14.cpp
// Passing arrays and individual array elements to functions.
#include
fig04_14.cpp
(1 of 3)
.c
om
using std::cout;
using std::endl;
#include
// appears strange
th
void modifyArray( int [], int );
void modifyElement( int );
an
using std::setw;
co
ng
Cú pháp cho mảng trong danh
sách tham số
// size of array a
// initialize a
u
du
o
ng
int main()
{
const int arraySize = 5;
int a[ arraySize ] = { 0, 1, 2, 3, 4 };
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cout << "Effects of passing entire array by reference:"
<< "\n\nThe values of the original array are:\n";
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 3 ) << a[ i ];
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Truyền tên mảng (a) và kích thước cho
hàm. Mảng truyền bằng tham chiếu
cout << endl;
// pass array a to modifyArray by reference
modifyArray( a, arraySize );
fig04_14.cpp
(2 of 3)
ng
co
// output modified array
for ( int j = 0; j < arraySize; j++ )
cout << setw( 3 ) << a[ j ];
.c
om
cout << "The values of the modified array are:\n";
du
o
ng
th
an
// output value of a[ 3 ]
cout << "\n\n\n"
<< "Effects of passing array element by value:"
<< "\n\nThe value of a[3] is " << a[ 3 ] << '\n';
u
// pass array element a[ 3 ] by value
modifyElement( a[ 3 ] );
1 phần tử mảng được truyền bằng giá trị;
giá trị phần tử gốc không thể bị thay đổi.
cu
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// output value of a[ 3 ]
cout << "The value of a[3] is " << a[ 3 ] << endl;
return 0;
// indicates successful termination
} // end main
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
ng
// multiply each array element by 2
for ( int k = 0; k < sizeOfArray; k++ )
b[ k ] *= 2;
.c
om
Tuy đặt tên là b, khi được gọi, mảng chỉ
// in function modifyArray, "b" points to
đến mảng a, nên hàm có thể thay đổi dữ
// the original array "a" in memory
liệu của a.
fig04_14.cpp
void modifyArray( int b[], int sizeOfArray )
(3 of 3)
{
co
} // end function modifyArray
u
du
o
ng
th
an
// in function modifyElement, "e" is a local copy of
// array element a[ 3 ] passed from main
Các phần tử đơn lẻ của mảng được
void modifyElement( int e )
truyền bằng giá trị, và các giá trị gốc
{
không thể bị thay đổi.
// multiply parameter by 2
cout << "Value in modifyElement is "
<< ( e *= 2 ) << endl;
cu
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
} // end function modifyElement
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Effects of passing entire array by reference:
the original array are:
4
the modified array are:
8
fig04_14.cpp
output (1 of 1)
.c
om
The values of
0 1 2 3
The values of
0 2 4 6
co
ng
Effects of passing array element by value:
cu
u
du
o
ng
th
an
The value of a[3] is 6
Value in modifyElement is 12
The value of a[3] is 6
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.15: fig04_15.cpp
// Demonstrating the const type qualifier.
#include
// function prototype
ng
void tryToModifyArray( const int [] );
.c
om
using std::cout;
using std::endl;
Tham số mảng được khai báo
là const. Mảng không thểfig04_15.cpp
bị
sửa đổi, kể cả khi nó được (1 of 2)
truyền bằng tham chiếu.
th
an
co
int main()
{
int a[] = { 10, 20, 30 };
ng
tryToModifyArray( a );
// indicates successful termination
u
return 0;
du
o
cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n';
} // end main
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// In function tryToModifyArray, "b" cannot be used
// to modify the original array "a" in main.
void tryToModifyArray( const int b[] )
{
b[ 0 ] /= 2;
// error
b[ 1 ] /= 2;
// error
b[ 2 ] /= 2;
// error
.c
om
fig04_15.cpp
(2 of 2)
u
du
o
ng
th
an
co
ng
} // end function tryToModifyArray
cu
22
23
24
25
26
27
28
29
30
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Sắp xếp mảng
4.6
.c
om
• Sắp xếp dữ liệu
ng
– Là một ứng dụng quan trọng
– Hầu hết mọi cơ quan/tổ chức đều phải sắp xếp dữ liệu
co
• Một khối lượng khổng lồ dữ liệu cần được sắp xếp
an
• Xếp nổi bọt (Bubble sort)
du
o
ng
th
– Duyệt mảng vài lần
– So sánh cặp phần tử liên tiếp
u
• Nếu thứ tự tăng (hoặc bằng nhau), không thay đổi gì
• Nếu thứ tự giảm, tráo đổi hai phần tử
cu
– Lặp lại các bước trên cho mọi phần tử
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Ví dụ:
.c
om
Sắp xếp mảng
4.6
– Đi từ trái sang phải, và tráo các phần tử khi cần thiết
u
du
o
ng
th
an
co
Dãy gốc:
3 4 2 7 6
Lần duyệt 1:
3 2 4 6 7 (tráo đổi phần tử)
Lần duyệt 2:
2 3 4 6 7
Lần duyệt 3:
2 3 4 6 7 (không cần thay đổi)
Lần duyệt 4:
2 3 4 6 7
Lần duyệt 5:
2 3 4 6 7
Phần tử nhỏ “nổi" lên trên (như số 2 trong ví dụ)
cu
–
–
–
–
–
–
–
ng
• Một lần duyệt cho mỗi phần tử
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Sắp xếp mảng
4.6
.c
om
• Tráo đổi các biến
ng
int x = 3, y = 4;
y = x;
x = y;
th
du
o
y = 4, temp = 0;
// temp là 3
// x là 4
// y là 3
cu
int x = 3,
temp = x;
x = y;
y = temp;
u
• Giải pháp
ng
– Cả x và y đều là 3!
– Cần có biến tạm
an
co
• Cái gì xảy ra?
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.16: fig04_16.cpp
// This program sorts an array's values into ascending order.
#include
fig04_16.cpp
(1 of 3)
.c
om
using std::cout;
using std::endl;
ng
#include
co
using std::setw;
du
o
ng
th
an
int main()
{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold; // temporary location used to swap array elements
u
cout << "Data items in original order\n";
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << a[ i ];
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Duyệt 1 lần cho mỗi phần tử
// bubble sort
của mảng.
// loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )
.c
om
// loop to control number of comparisons per pass
for ( int j = 0; j < arraySize - 1; j++ )
fig04_16.cpp
(2 of 3)
th
an
co
ng
// compare side-by-side elements and swap them if
// first element is greater than second element
if ( a[ j ] > a[ j + 1 ] ) {
Nếu phần tử bên trái (chỉ số j)
hold = a[ j ];
lớn hơn phần tử bên phải (chỉ số
a[ j ] = a[ j + 1 ];
j + 1), thì ta tráo đổi chúng.
a[ j + 1 ] = hold;
Nhớ sử dụng biến tạm.
u
du
o
ng
} // end if
cu
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
cout << "\nData items in ascending order\n";
// output sorted array
for ( int k = 0; k < arraySize; k++ )
cout << setw( 4 ) << a[ k ];
.c
om
fig04_16.cpp
(3 of 3)
cout << endl;
ng
// indicates successful termination
co
return 0;
} // end main
45
37
68
89
cu
u
du
o
ng
Data items in original order
2
6
4
8 10 12 89 68
Data items in ascending order
2
4
6
8 10 12 37 45
th
an
40
41
42
43
44
45
46
47
48
49
50
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_16.cpp
output (1 of 1)
4.7
Ví dụ: sử dụng mảng để tính
Mean, Median và Mode
.c
om
• Mean
– Giá trị trung bình (tổng/số phần tử)
ng
• Median
du
o
• Mode
ng
th
an
co
– Giá trị ở giữa dãy đã được sắp xếp
– 1, 2, 3, 4, 5 (3 là median)
– Nếu số phần tử là số chẵn, lấy trung bình của 2 số giữa
cu
u
– Giá trị xuất hiện nhiều nhất
– 1, 1, 1, 2, 3, 3, 4, 5 (1 là mode)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.17: fig04_17.cpp
// This program introduces the topic of survey data analysis.
// It computes the mean, median, and mode of the data.
#include
ng
.c
om
std::cout;
std::endl;
std::fixed;
std::showpoint;
co
using
using
using
using
an
#include
ng
du
o
mean( const int [], int );
median( int [], int );
mode( int [], int [], int );
bubbleSort( int[], int );
printArray( const int[], int );
u
void
void
void
void
void
th
using std::setw;
using std::setprecision;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main()
{
const int responseSize = 99;
CuuDuongThanCong.com
// size of array responses
https://fb.com/tailieudientucntt
fig04_17.cpp
(1 of 8)
// initialize array frequency
.c
om
ng
8, 9,
7, 8,
8, 7,
8, 9,
9, 2,
5, 3,
6, 4,
7, 8,
5, 6,
7 };
fig04_17.cpp
(2 of 8)
ng
th
an
// initialize array responses
int response[ responseSize ] =
{ 6, 7, 8, 9, 8, 7, 8, 9,
7, 8, 9, 5, 9, 8, 7, 8,
6, 7, 8, 9, 3, 9, 8, 7,
7, 8, 9, 8, 9, 8, 9, 7,
6, 7, 8, 7, 8, 7, 9, 8,
7, 8, 9, 8, 9, 8, 9, 7,
5, 6, 7, 2, 5, 3, 9, 4,
7, 8, 9, 6, 8, 7, 8, 9,
7, 4, 4, 2, 5, 3, 8, 7,
4, 5, 6, 1, 6, 5, 7, 8,
co
int frequency[ 10 ] = { 0 };
u
du
o
// process responses
mean( response, responseSize );
median( response, responseSize );
mode( frequency, response, responseSize );
return 0;
cu
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// indicates successfu...
om
ng
co
th
an
Ngôn ngữ lập trình C++
cu
u
du
o
ng
Chương 4 – Mảng
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
u
du
o
ng
th
an
co
ng
Giới thiệu
Mảng
Khai báo mảng
Ví dụ về sử dụng mảng
Truyền tham số cho hàm
Sắp xếp mảng
Ví dụ: Dùng mảng tính Mean, Median và Mode
Tìm kiếm trên mảng: Tìm kiếm Tuyến tính và tìm kiếm Nhị phân
Mảng nhiều chiều
cu
Đề mục
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.9
.c
om
Chương 4 – Mảng
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Giới thiệu
4.1
.c
om
• Mảng (array)
co
ng
– Cấu trúc của những phần tử dữ liệu có liên quan
– Thực thể tĩnh (giữ nguyên kích thước trong suốt chương
trình)
an
• Một vài loại mảng
cu
u
du
o
ng
th
– mảng dựa vào con trỏ (Pointer-based arrays) (C-like)
– mảng là đối tượng (Arrays as objects) (C++)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Mảng
4.2
.c
om
• Mảng
co
• Truy nhập đến 1 phần tử
ng
– Tập hợp các vùng nhớ liên tiếp
– Cùng tên, cùng kiểu (int, char, ...)
ng
th
an
– Chỉ ra tên mảng và vị trí - position (chỉ số - index)
– Cú pháp: tên_mảng[ chỉ_số ]
du
o
– Phần tử đầu tiên ở vị trí 0
• Mảng c có n phần tử
cu
u
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Phần tử thứ N ở vị trí thứ N-1
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Mảng
4.2
.c
om
• Phần tử của mảng cũng như các biến khác
– Gán giá trị và in mảng số nguyên c
co
ng
c[ 0 ] = 3;
cout << c[ 0 ];
an
• Có thể sử dụng các phép toán trong cặp ngoặc vuông
cu
u
du
o
ng
th
c[ 5 – 2 ] cũng giống c[3]
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
c[1]
6
c[2]
0
72
an
c[3]
1543
-89
c[6]
0
c[7]
62
c[8]
-3
c[9]
1
c[10]
6453
c[11]
78
cu
u
du
o
c[5]
ng
th
c[4]
ng
-45
co
c[0]
.c
om
Tên mảng
(Lưu ý rằng mọi phần tử
của mảng này đều có cùng
tên, c)
Chỉ số của phần tử
trong mảng c
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
4.3
Khai báo mảng
co
• Bất cứ kiểu dữ liệu nào
ng
– Tên
– Kiểu của mảng
.c
om
• Khi khai báo mảng, chỉ rõ
th
an
– Số phần tử
– type arrayName[ arraySize ];
du
o
ng
int c[ 10 ]; // mảng của 10 số nguyên
float d[ 3284 ]; // mảng của 3284 số thực
• Khai báo nhiều mảng cùng kiểu
cu
u
– Sử dụng dấu phẩy như với các biến bình thường
int b[ 100 ], x[ 27 ];
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Khởi tạo mảng
ng
– Dùng vòng lặp khởi tạo từng phần tử
– Khởi tạo cả danh sách
.c
om
Ví dụ về sử dụng mảng
4.4
co
• Chỉ rõ từng phần tử khi khai báo mảng
int n[ 5 ] = { 1, 2, 3, 4, 5 };
ng
th
an
• Nếu trong danh sách không có đủ số giá trị khởi tạo, các phần tử ở
bên phải nhất sẽ nhận giá trị 0
• Nếu danh sách thừa sẽ gây lỗi cú pháp
du
o
– Khởi tạo giá trị bằng 0 cho tất cả các phần tử
int n[ 5 ] = { 0 };
cu
u
– Nếu không khai báo kích thước mảng, kích thước của danh sách
các giá trị khởi tạo sẽ quyết định kích thước mảng
int n[] = { 1, 2, 3, 4, 5 };
• Có 5 giá trị khởi tạo, do đó mảng có 5 phần tử
• Nếu không khai báo kích thước mảng thì phải khởi tạo khi khai báo
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.3: fig04_03.cpp
// Initializing an array.
#include
fig04_03.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
ng
#include
using std::setw;
co
an
th
Khởi tạo mảng bằng vòng lặp for.
// n is an array of 10 integers
ng
int main()
{
int n[ 10 ];
Khai báo mảng 10 phần tử số nguyên.
Chú ý rằng mảng gồm các phẩn tử
từ n[0] đến n[9].
u
du
o
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
n[ i ] = 0;
// set element at location i to 0
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array n in tabular format
for ( int j = 0; j < 10; j++ )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
26
27
28
return 0;
// indicates successful termination
} // end main
u
du
o
ng
th
an
co
ng
Value
0
0
0
0
0
0
0
0
0
0
cu
Element
0
1
2
3
4
5
6
7
8
9
.c
om
fig04_03.cpp
(2 of 2)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_03.cpp
output (1 of 1)
// Fig. 4.4: fig04_04.cpp
// Initializing an array with a declaration.
#include
fig04_04.cpp
(1 of 1)
.c
om
using std::cout;
using std::endl;
ng
#include
using std::setw;
co
Lưu ý cách dùng danh sách
khởi tạo cho mảng.
du
o
ng
th
an
int main()
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
cout << "Element" << setw( 13 ) << "Value" << endl;
u
// output contents of array n in tabular format
for ( int i = 0; i < 10; i++ )
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
return 0;
// indicates successful termination
} // end main
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Value
32
27
64
18
95
14
90
70
60
37
u
du
o
ng
th
an
co
ng
.c
om
fig04_04.cpp
output (1 of 1)
cu
Element
0
1
2
3
4
5
6
7
8
9
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Kích thước của mảng
.c
om
Ví dụ về sử dụng mảng
4.4
– Có thể được xác định bằng hằng số (const)
ng
• const int size = 20;
cu
u
du
o
ng
th
an
co
– Hằng số không thể thay đổi
– Hằng phải được khởi tạo khi khai báo
– Còn được gọi là “named constant” (giá trị được đặt tên) hoặc
“read-only variable” (biến chỉ đọc)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.5: fig04_05.cpp
// Initialize array s to the even integers from 2 to 20.
#include
fig04_05.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
ng
#include
Chú ý từ khoá const. Chỉ có
các biến const được dùng
để khai
báo kích
thướcsize
mảng.
to
specify
array
int s[ arraySize ];
du
o
ng
th
an
int main()
{
// constant variable can be used
const int arraySize = 10;
co
using std::setw;
// array s has 10 elements
u
Chương trình dễ thay đổi hơn khi ta
dùng hằng (const) cho kích thước của
for ( int i = 0; i < arraySize; i++ ) // set the values
mảng.
s[ i ] = 2 + 2 * i;
Ta có thể thay đổi arraySize, và tất
cả các vòng lặp vẫn hoạt động bình
cout << "Element" << setw( 13 ) << "Value" << endl;
thường (nếu không, ta phải sửa mọi
vòng lặp trong chương trình).
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// output contents of array s in tabular format
for ( int j = 0; j < arraySize; j++ )
cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
// indicates successful termination
.c
om
return 0;
co
an
th
ng
du
o
u
Value
2
4
6
8
10
12
14
16
18
20
ng
} // end main
Element
0
1
2
3
4
5
6
7
8
9
fig04_05.cpp
(2 of 2)
cu
24
25
26
27
28
29
30
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_05.cpp
output (1 of 1)
// Fig. 4.6: fig04_06.cpp
// Using a properly initialized constant variable.
#include
fig04_06.cpp
(1 of 1)
.c
om
using std::cout;
using std::endl;
// initialized constant variable
co
int main()
{
const int x = 7;
ng
Khởi tạo hằng
th
an
cout << "The value of constant variable x is: "
<< x << endl;
} // end main
ng
// indicates successful termination
du
o
return 0;
cu
u
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
The value of constant variable x is: 7
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_06.cpp
output (1 of 1)
// Fig. 4.7: fig04_07.cpp
// A const object must be initialized.
Lỗi cú pháp do không khởi tạo hằng.
Sửa giá trị của hằng cũng là một lỗi.
fig04_07.cpp
(1 of 1)
// Error: x must be initialized
.c
om
int main()
{
const int x;
// Error: cannot modify a const variable
return 0;
// indicates successful termination
co
ng
x = 7;
an
} // end main
ng
th
1
2
3
4
5
6
7
8
9
10
11
12
cu
u
du
o
d:\cpphtp4_examples\ch04\Fig04_07.cpp(6) : error C2734: 'x' :
const object must be initialized if not extern
d:\cpphtp4_examples\ch04\Fig04_07.cpp(8) : error C2166:
l-value specifies const object
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_07.cpp
output (1 of 1)
// Fig. 4.8: fig04_08.cpp
// Compute the sum of the elements of the array.
#include
fig04_08.cpp
(1 of 1)
.c
om
using std::cout;
using std::endl;
co
ng
int main()
{
const int arraySize = 10;
th
an
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ng
int total = 0;
u
du
o
// sum contents of array a
for ( int i = 0; i < arraySize; i++ )
total += a[ i ];
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cout << "Total of array element values is " << total << endl;
return 0;
} // end main
// indicates successful termination
Total of array element values is 55
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_08.cpp
output (1 of 1)
.c
om
Value
19
3
15
7
11
9
13
5
17
1
ng
co
du
o
ng
th
an
// Fig. 4.9: fig04_09.cpp
// Histogram printing program.
Element
#include
0
1
using std::cout;
2
using std::endl;
3
4
#include
5
6
using std::setw;
7
8
int main()
9
{
Histogram
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
u
const int arraySize = 10;
int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fig04_09.cpp
(1 of 2)
cout << "Element" << setw( 13 ) << "Value"
<< setw( 17 ) << "Histogram" << endl;
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// for each element of array n, output a bar in histogram
for ( int i = 0; i < arraySize; i++ ) {
cout << setw( 7 ) << i << setw( 13 )
In số dấu saofig04_09.cpp
(*) tương ứng
<< n[ i ] << setw( 9 );
với giá trị của
(2 phần
of 2) tử n[i].
ng
// start next line of output
co
cout << endl;
CuuDuongThanCong.com
Value
19
3
15
7
11
9
13
5
17
1
ng
du
o
Element
0
1
2
3
4
5
6
7
8
9
th
// indicates successful termination
u
} // end main
an
} // end outer for structure
return 0;
// print one bar
.c
om
for ( int j = 0; j < n[ i ]; j++ )
cout << '*';
cu
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Histogram
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
https://fb.com/tailieudientucntt
fig04_09.cpp
output (1 of 1)
// Fig. 4.10: fig04_10.cpp
// Roll a six-sided die 6000 times.
#include
fig04_10.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
#include
ng
Viết lại một chương trình cũ. Một
mảng được sử dụng thay cho 6
biến thường, và các phần tử dễ
dàng cập nhật hơn (không cần sử
dụng switch).
co
using std::setw;
th
an
#include
#include
du
o
ng
int main()
{
const int arraySize = 7;
int frequency[ arraySize ] = { 0 };
Dòng lệnh này tạo ra một số trong
khoảng 1 đến 6 và tăng phần tử
// seed random-number generator
frequency[] có chỉ số đó.
u
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
srand( time( 0 ) );
// roll die 6000 times
for ( int roll = 1; roll <= 6000; roll++ )
++frequency[ 1 + rand() % 6 ]; // replaces 20-line switch
// of Fig. 3.8
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
cout << "Face" << setw( 13 ) << "Frequency" << endl;
ng
// indicates successful termination
co
return 0;
.c
om
// output frequency elements 1-6 in tabular format
for ( int face = 1; face < arraySize; face++ )
cout << setw( 4 ) << face
<< setw( 13 ) << frequency[ face ] << endl;
} // end main
ng
du
o
u
Frequency
1003
1004
999
980
1013
1001
cu
Face
1
2
3
4
5
6
th
an
26
27
28
29
30
31
32
33
34
35
36
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_10.cpp
(2 of 2)
fig04_10.cpp
output (1 of 1)
// Fig. 4.11: fig04_11.cpp
***modified***
// Student mark statistic program.
#include
fig04_11.cpp
(1 of 2)
.c
om
using std::cout;
using std::endl;
ng
#include
co
using std::setw;
du
o
ng
th
an
int main()
{
// define array sizes
const int markSize = 40;
// size of array of marks
const int frequencySize = 11; // size of array frequency
u
// place student marks in array of marks
int marks[ markSize ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8,
10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7,
5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// initialize frequency counters to 0
int frequency[ frequencySize ] = { 0 };
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
.c
om
// for each student's mark, select value of an element of array
// responses and use that value as subscript in array
// frequency to determine element to increment
fig04_11.cpp
for ( int student = 0; student < markSize; student++ )
(2 of 2)
++frequency[ marks[student] ];
ng
// display results
cout << "Rating" << setw( 17 ) << "Frequency" << endl;
th
an
co
// output frequencies in tabular format
for ( int rating = 1; rating < frequencySize; rating++ )
cout << setw( 6 ) << rating
<< setw( 17 ) << frequency[ rating ] << endl;
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
ng
Rating
1
2
3
4
5
6
7
8
9
10
du
o
} // end main
// indicates successful termination
marks[student] là điểm (từ 1 đến 10).
Giá trị này quyết định chỉ số của phần tử
frequency[] cần tăng.
u
return 0;
cu
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Frequency
2
2
2
2
5
11
5
7
1
3
Ví dụ về sử dụng mảng
4.4
.c
om
• Xâu - string (xem thêm ở chương 5)
ng
– Mảng của các ký tự
– Mọi xâu đều kết thúc với ký tự null ('\0')
co
– Ví dụ
an
• char string1[] = "hello";
th
– Ký tự null tự động được thêm vào, xâu có 6 phần tử
du
o
ng
• char string1[] = { 'h', 'e', 'l', 'l',
'o', '\0' };
– Chỉ số cũng giống như đối với mảng
cu
u
String1[ 0 ] bằng 'h'
string1[ 2 ] bằng 'l'
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Nhập từ bàn phím bằng cin
ng
char string2[ 10 ];
cin >> string2;
.c
om
Ví dụ về sử dụng mảng
4.4
co
– Ghi dữ liệu vào của người dùng vào xâu
th
an
• Dừng lại ở ký tự trắng đầu tiên (tab, newline, blank…)
• Thêm vào ký tự null
ng
– Nếu nhập quá nhiều, dữ liệu sẽ tràn mảng
u
cu
• In xâu
du
o
• Ta cần phải tránh điều này (mục 5.12 sẽ giải thích phương
pháp)
– cout << string2 << endl;
• Không sử dụng được với các mảng có kiểu dữ liệu khác
– In các ký tự cho đến khi gặp null
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4_12: fig04_12.cpp
// Treating character arrays as strings.
#include
fig04_12.cpp
(1 of 2)
.c
om
using std::cout;
using std::cin;
using std::endl;
Hai cách khác nhau để khai báo
xâu. string2 được khởi tạo và
kích thước được xác định tự động.
th
an
co
ng
int main()
{
char string1[ 20 ],
// reserves 20 characters
char string2[] = "string literal"; // reserves 15 characters
Ví dụ về đọc xâu từ bàn phím và in ra.
du
o
ng
// read string from user into array string2
cout << "Enter the string \"hello there\": ";
cin >> string1; // reads "hello" [space terminates input]
u
// output strings
cout << "string1 is: " << string1
<< "\nstring2 is: " << string2;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
cout << "\nstring1 with spaces between characters is:\n";
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// output characters until null character is reached
for ( int i = 0; string1[ i ] != '\0'; i++ )
cout << string1[ i ] << ' ';
ng
.c
om
Có thể truy nhập xâu
giống
fig04_12.cpp
như đối với mảng. Vòng
(2 of lặp
2)
cin >> string1; // reads "there"
kết thúc khi gặp ký tự null.
cout << "\nstring1 is: " << string1 << endl;
fig04_12.cpp
output (1 of 1)
return 0; // indicates successful termination
} // end main
an
co
24
25
26
27
28
29
30
31
32
33
cu
u
du
o
ng
th
Enter the string "hello there": hello there
string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
h e l l o
string1 is: there
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Ví dụ về sử dụng mảng
4.4
.c
om
• Kiểu lưu trữ tĩnh – static storage (chương 3)
an
co
ng
– Nếu là static, các biến địa phương lưu lại giá trị giữa các
lần gọi hàm
– chỉ được nhìn thấy trong thân hàm
– Có thể khai báo mảng địa phương là static
ng
th
• được khởi tạo về 0
static int array[3];
du
o
• Nếu không phải static
cu
u
– Được tạo (và huỷ) tại mỗi lần gọi hàm
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.13: fig04_13.cpp
// Static arrays are initialized to zero.
#include
fig04_13.cpp
(1 of 3)
ng
// function prototype
// function prototype
co
void staticArrayInit( void );
void automaticArrayInit( void );
.c
om
using std::cout;
using std::endl;
du
o
ng
th
an
int main()
{
cout << "First call to each function:\n";
staticArrayInit();
automaticArrayInit();
u
cout << "\n\nSecond call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << endl;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
return 0;
// indicates successful termination
} // end main
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_13.cpp
(2 of 3)
.c
om
// function to demonstrate a static local array
void staticArrayInit( void )
Mảng static, khởi tạo về 0 tại
{
lần gọi hàm đầu tiên.
// initializes elements to 0 first time function is called
static int array1[ 3 ];
cout << "\nValues on entering staticArrayInit:\n";
an
co
ng
// output contents of array1
for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = " << array1[ i ] << "
th
cout << "\nValues on exiting staticArrayInit:\n";
ng
contents of array1
3; j++ )
<< j << "] = "
j ] += 5 ) << " ";
Dữ liệu trong mảng bị thay đổi,
các thay đổi được bảo toàn.
u
du
o
// modify and output
for ( int j = 0; j <
cout << "array1["
<< ( array1[
";
cu
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
} // end function staticArrayInit
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
.c
om
// function to demonstrate an automatic local array
void automaticArrayInit( void )
Mảng automatic, được tạo lại
{
tại mỗi lần gọi hàm.
fig04_13.cpp
// initializes elements each time function is called
(3 of 3)
int array2[ 3 ] = { 1, 2, 3 };
cout << "\n\nValues on entering automaticArrayInit:\n";
an
co
ng
// output contents of array2
for ( int i = 0; i < 3; i++ )
cout << "array2[" << i << "] = " << array2[ i ] << "
";
th
cout << "\nValues on exiting automaticArrayInit:\n";
ng
contents of array2
3; j++ )
<< j << "] = "
j ] += 5 ) << " ";
u
du
o
// modify and output
for ( int j = 0; j <
cout << "array2["
<< ( array2[
Tuy mảng bị thay đổi, nó sẽ bị
huỷ khi hàm kết thúc và thayt
đổi trong dữ liệu sẽ bị mất.
cu
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
} // end function automaticArrayInit
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
First call to each function:
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
.c
om
Values on
array2[0]
Values on
array2[0]
fig04_13.cpp
output (1 of 1)
ng
entering staticArrayInit:
= 0 array1[1] = 0 array1[2] = 0
exiting staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
an
co
Values on
array1[0]
Values on
array1[0]
th
Second call to each function:
entering staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
exiting staticArrayInit:
= 10 array1[1] = 10 array1[2] = 10
Values on
array2[0]
Values on
array2[0]
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
cu
u
du
o
ng
Values on
array1[0]
Values on
array1[0]
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Truyền tham số cho hàm
4.5
.c
om
• Dùng tên mảng, bỏ cặp ngoặc vuông
– Truyền mảng myArray cho hàm myFunction
ng
int myArray[ 24 ];
myFunction( myArray, 24 );
co
– Kích thước mảng thường được truyền, nhưng không nhất thiết
an
• Có ích khi dùng để duyệt tất cả các phần tử
th
• Mảng được truyền bằng tham chiếu (passed-by-reference)
du
o
ng
– Hàm có thể thay đổi dữ liệu gốc của mảng
– Tên mảng có giá trị bằng địa chỉ của phần tử đầu tiên
u
• Hàm biết mảng được lưu ở đâu.
• Hàm có thể sửa đổi dữ liệu ghi trong mảng
cu
• Các phần tử mảng được truyền bằng giá trị (passed-byvalue)
– Như các biến thông thường
– square( myArray[3] );
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Truyền tham số cho hàm
4.5
.c
om
• Các hàm dùng mảng làm đối số
– Function prototype
co
ng
• void modifyArray( int b[], int arraySize );
• void modifyArray( int [], int );
an
– Trong prototype, tên không bắt buộc
th
• cả hai hàm lấy đối số là một mảng số nguyên và 1 số nguyên
ng
– Không ghi cần kích thước mảng trong cặp ngoặc
du
o
• Trình biên dịch bỏ qua
– Nếu khai báo 1 tham số là const
cu
u
• đối số đó sẽ không thể bị thay đổi (chương trình dịch báo lỗi)
• void doNotModify( const int [] );
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.14: fig04_14.cpp
// Passing arrays and individual array elements to functions.
#include
fig04_14.cpp
(1 of 3)
.c
om
using std::cout;
using std::endl;
#include
// appears strange
th
void modifyArray( int [], int );
void modifyElement( int );
an
using std::setw;
co
ng
Cú pháp cho mảng trong danh
sách tham số
// size of array a
// initialize a
u
du
o
ng
int main()
{
const int arraySize = 5;
int a[ arraySize ] = { 0, 1, 2, 3, 4 };
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cout << "Effects of passing entire array by reference:"
<< "\n\nThe values of the original array are:\n";
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 3 ) << a[ i ];
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Truyền tên mảng (a) và kích thước cho
hàm. Mảng truyền bằng tham chiếu
cout << endl;
// pass array a to modifyArray by reference
modifyArray( a, arraySize );
fig04_14.cpp
(2 of 3)
ng
co
// output modified array
for ( int j = 0; j < arraySize; j++ )
cout << setw( 3 ) << a[ j ];
.c
om
cout << "The values of the modified array are:\n";
du
o
ng
th
an
// output value of a[ 3 ]
cout << "\n\n\n"
<< "Effects of passing array element by value:"
<< "\n\nThe value of a[3] is " << a[ 3 ] << '\n';
u
// pass array element a[ 3 ] by value
modifyElement( a[ 3 ] );
1 phần tử mảng được truyền bằng giá trị;
giá trị phần tử gốc không thể bị thay đổi.
cu
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// output value of a[ 3 ]
cout << "The value of a[3] is " << a[ 3 ] << endl;
return 0;
// indicates successful termination
} // end main
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
ng
// multiply each array element by 2
for ( int k = 0; k < sizeOfArray; k++ )
b[ k ] *= 2;
.c
om
Tuy đặt tên là b, khi được gọi, mảng chỉ
// in function modifyArray, "b" points to
đến mảng a, nên hàm có thể thay đổi dữ
// the original array "a" in memory
liệu của a.
fig04_14.cpp
void modifyArray( int b[], int sizeOfArray )
(3 of 3)
{
co
} // end function modifyArray
u
du
o
ng
th
an
// in function modifyElement, "e" is a local copy of
// array element a[ 3 ] passed from main
Các phần tử đơn lẻ của mảng được
void modifyElement( int e )
truyền bằng giá trị, và các giá trị gốc
{
không thể bị thay đổi.
// multiply parameter by 2
cout << "Value in modifyElement is "
<< ( e *= 2 ) << endl;
cu
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
} // end function modifyElement
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Effects of passing entire array by reference:
the original array are:
4
the modified array are:
8
fig04_14.cpp
output (1 of 1)
.c
om
The values of
0 1 2 3
The values of
0 2 4 6
co
ng
Effects of passing array element by value:
cu
u
du
o
ng
th
an
The value of a[3] is 6
Value in modifyElement is 12
The value of a[3] is 6
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.15: fig04_15.cpp
// Demonstrating the const type qualifier.
#include
// function prototype
ng
void tryToModifyArray( const int [] );
.c
om
using std::cout;
using std::endl;
Tham số mảng được khai báo
là const. Mảng không thểfig04_15.cpp
bị
sửa đổi, kể cả khi nó được (1 of 2)
truyền bằng tham chiếu.
th
an
co
int main()
{
int a[] = { 10, 20, 30 };
ng
tryToModifyArray( a );
// indicates successful termination
u
return 0;
du
o
cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n';
} // end main
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// In function tryToModifyArray, "b" cannot be used
// to modify the original array "a" in main.
void tryToModifyArray( const int b[] )
{
b[ 0 ] /= 2;
// error
b[ 1 ] /= 2;
// error
b[ 2 ] /= 2;
// error
.c
om
fig04_15.cpp
(2 of 2)
u
du
o
ng
th
an
co
ng
} // end function tryToModifyArray
cu
22
23
24
25
26
27
28
29
30
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Sắp xếp mảng
4.6
.c
om
• Sắp xếp dữ liệu
ng
– Là một ứng dụng quan trọng
– Hầu hết mọi cơ quan/tổ chức đều phải sắp xếp dữ liệu
co
• Một khối lượng khổng lồ dữ liệu cần được sắp xếp
an
• Xếp nổi bọt (Bubble sort)
du
o
ng
th
– Duyệt mảng vài lần
– So sánh cặp phần tử liên tiếp
u
• Nếu thứ tự tăng (hoặc bằng nhau), không thay đổi gì
• Nếu thứ tự giảm, tráo đổi hai phần tử
cu
– Lặp lại các bước trên cho mọi phần tử
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
• Ví dụ:
.c
om
Sắp xếp mảng
4.6
– Đi từ trái sang phải, và tráo các phần tử khi cần thiết
u
du
o
ng
th
an
co
Dãy gốc:
3 4 2 7 6
Lần duyệt 1:
3 2 4 6 7 (tráo đổi phần tử)
Lần duyệt 2:
2 3 4 6 7
Lần duyệt 3:
2 3 4 6 7 (không cần thay đổi)
Lần duyệt 4:
2 3 4 6 7
Lần duyệt 5:
2 3 4 6 7
Phần tử nhỏ “nổi" lên trên (như số 2 trong ví dụ)
cu
–
–
–
–
–
–
–
ng
• Một lần duyệt cho mỗi phần tử
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Sắp xếp mảng
4.6
.c
om
• Tráo đổi các biến
ng
int x = 3, y = 4;
y = x;
x = y;
th
du
o
y = 4, temp = 0;
// temp là 3
// x là 4
// y là 3
cu
int x = 3,
temp = x;
x = y;
y = temp;
u
• Giải pháp
ng
– Cả x và y đều là 3!
– Cần có biến tạm
an
co
• Cái gì xảy ra?
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.16: fig04_16.cpp
// This program sorts an array's values into ascending order.
#include
fig04_16.cpp
(1 of 3)
.c
om
using std::cout;
using std::endl;
ng
#include
co
using std::setw;
du
o
ng
th
an
int main()
{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold; // temporary location used to swap array elements
u
cout << "Data items in original order\n";
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << a[ i ];
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
Duyệt 1 lần cho mỗi phần tử
// bubble sort
của mảng.
// loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )
.c
om
// loop to control number of comparisons per pass
for ( int j = 0; j < arraySize - 1; j++ )
fig04_16.cpp
(2 of 3)
th
an
co
ng
// compare side-by-side elements and swap them if
// first element is greater than second element
if ( a[ j ] > a[ j + 1 ] ) {
Nếu phần tử bên trái (chỉ số j)
hold = a[ j ];
lớn hơn phần tử bên phải (chỉ số
a[ j ] = a[ j + 1 ];
j + 1), thì ta tráo đổi chúng.
a[ j + 1 ] = hold;
Nhớ sử dụng biến tạm.
u
du
o
ng
} // end if
cu
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
cout << "\nData items in ascending order\n";
// output sorted array
for ( int k = 0; k < arraySize; k++ )
cout << setw( 4 ) << a[ k ];
.c
om
fig04_16.cpp
(3 of 3)
cout << endl;
ng
// indicates successful termination
co
return 0;
} // end main
45
37
68
89
cu
u
du
o
ng
Data items in original order
2
6
4
8 10 12 89 68
Data items in ascending order
2
4
6
8 10 12 37 45
th
an
40
41
42
43
44
45
46
47
48
49
50
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
fig04_16.cpp
output (1 of 1)
4.7
Ví dụ: sử dụng mảng để tính
Mean, Median và Mode
.c
om
• Mean
– Giá trị trung bình (tổng/số phần tử)
ng
• Median
du
o
• Mode
ng
th
an
co
– Giá trị ở giữa dãy đã được sắp xếp
– 1, 2, 3, 4, 5 (3 là median)
– Nếu số phần tử là số chẵn, lấy trung bình của 2 số giữa
cu
u
– Giá trị xuất hiện nhiều nhất
– 1, 1, 1, 2, 3, 3, 4, 5 (1 là mode)
CuuDuongThanCong.com
https://fb.com/tailieudientucntt
// Fig. 4.17: fig04_17.cpp
// This program introduces the topic of survey data analysis.
// It computes the mean, median, and mode of the data.
#include
ng
.c
om
std::cout;
std::endl;
std::fixed;
std::showpoint;
co
using
using
using
using
an
#include
ng
du
o
mean( const int [], int );
median( int [], int );
mode( int [], int [], int );
bubbleSort( int[], int );
printArray( const int[], int );
u
void
void
void
void
void
th
using std::setw;
using std::setprecision;
cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main()
{
const int responseSize = 99;
CuuDuongThanCong.com
// size of array responses
https://fb.com/tailieudientucntt
fig04_17.cpp
(1 of 8)
// initialize array frequency
.c
om
ng
8, 9,
7, 8,
8, 7,
8, 9,
9, 2,
5, 3,
6, 4,
7, 8,
5, 6,
7 };
fig04_17.cpp
(2 of 8)
ng
th
an
// initialize array responses
int response[ responseSize ] =
{ 6, 7, 8, 9, 8, 7, 8, 9,
7, 8, 9, 5, 9, 8, 7, 8,
6, 7, 8, 9, 3, 9, 8, 7,
7, 8, 9, 8, 9, 8, 9, 7,
6, 7, 8, 7, 8, 7, 9, 8,
7, 8, 9, 8, 9, 8, 9, 7,
5, 6, 7, 2, 5, 3, 9, 4,
7, 8, 9, 6, 8, 7, 8, 9,
7, 4, 4, 2, 5, 3, 8, 7,
4, 5, 6, 1, 6, 5, 7, 8,
co
int frequency[ 10 ] = { 0 };
u
du
o
// process responses
mean( response, responseSize );
median( response, responseSize );
mode( frequency, response, responseSize );
return 0;
cu
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// indicates successfu...
 








Các ý kiến mới nhất