FP - Topic 5 - Array
FP - Topic 5 - Array
Fundamentals of Programming
Array
Rev.240901
HCM City 1
Content
• One-dimensional array
• Two-dimensional array
2
How to Store Multiple Integers
• Example
– How to store 3 integers?
=> Declare 3 variables: int a1, a2, a3;
– How to store 100 integers?
=> Declare 100 integer type variables, one by one
(impractical)!
– When the program is running, the user decides the
number of integers needed. How to store them?
=> Can't do it!
• Solution
– The new data type allows storing a range of integers
and is easy to retrieve.
3
What is an Array?
• Array:
– A structured data type defined by a programmer.
– Represents a sequence of variables of the same
type, such as:
▪ sequence of integers
▪ sequence of characters
4
Key Characteristics of Arrays
• Characteristics in C/C++:
– Fixed Dimensions: The dimensions (size) of an
array are set at the time of declaration and
cannot be changed.
– Continuous Memory Allocation: C/C++ always
assigns a continuous block of memory to an
array variable.
– Efficiency: Continuous memory allocation
enables efficient access and traversal of array
elements.
5
Declare array variables (explicit)
• Explicit
<data_type> <array_name>[<number of elements>];
<data_type> <array_name>[<N1>][<N2>]…[<Nn>];
int a[10];
0 1 2 3 4 5 6 7 8 9
int a[3][4];
0 1 2 3 4 5 6 7 8 9 10 11
a 0
1
2
7
Declare array variables (implicit)
• Syntax
– Implicit (via type declarations)
typedef <data_type> <array_type_name>[<N>];
typedef <data_type> <array_type_name>[<N1>]…[<Nn>];
<array_type_name> <array_name>;
• Example
0 1 2 3
a 2912 1706 0 0
10
Initialize values at declaration
• We can:
– Initialize all elements of an array to 0:
int a[4] = {0};
0 1 2 3
a 0 0 0 0
0 1 2 3
a 2912 1706 1506 1904
11
Access to an element
• By index
<array_name>[<index 0>][<index 1>]…[<index n-1>]
• Example
– Given array: 0 1 2 3
int a[4];
– Access
▪ Valid: a[0], a[1], a[2], a[3]
▪ Invalid: a[-1], a[4], a[5], …
=> The results are often not as expected!
12
Assign values to array
• When assigning values to arrays, we must
assign each element of the array directly.
– Cannot assign a value to the whole array at
once.
<destination array> = <source array>; //incorrect
<destination array>[<index i>] = <value>;
• Example
#define MAX 3
typedef int ARRAY[MAX];
ARRAY a = {1, 2, 3}, b;
b = a; // Incorrect
for (int i = 0; i < 3; i++) b[i] = a[i]; 13
Some common mistakes
• The declaration does not specify the number of elements
– int a[]; => int a[100];
• Use variables or constants to declare the number of
elements
– int n1 = 10; int a[n1]; => int a[10];
– const int n2 = 10; int a[n2]; => int a[10];
• Declaring and initializing are separate
– int a[4]; a = {2912, 1706, 1506, 1904};
=> int a[4] = {2912, 1706, 1506, 1904};
• Invalid array index
– int a[4];
– a[-1] = 1; a[10] = 0;
14
Pass the array to the function
• Pass the array to the function
– When declaring an array parameter in a function,
it resembles the array declaration.
void Sort(int a[100]);
• Function call
void InputArray(int a[], int &n);
void OutputArray(int a[], int n);
void main()
{
int a[100], n;
InputArray(a, n);
OutputArray(a, n);
} 16
Array of struct
• Can declare an array of structs to store multiple
records of the same type in a single array:
struct Student m1[10]; // Array of 10 struct Student
17
Exercise
• Write functions that perform each of the
following requirements:
1. Enter values for the array
2. Print out the array
3. Search for an element in the array
4. Check properties of arrays (e.g. a prime array)
5. Extract some elements from array
6. Splitting / Merging arrays
7. Find the smallest / largest value of the array
8. Sort array descending / ascending
9. Add / Delete / Edit an element to the array
18
Enter values for array
• Requirements
– Lets enter the array a, the number of elements n
• Idea
– Given an array with the number of elements is MAX.
– Enter the used number of elements (n) in the array.
– Enter each element for the array from index 0 to n - 1.
0 1 2 3 n4
-1 MAX - 1
… … …
19
Enter values for array
20
Display array
• Requirements
– Given array a and the number of elements n, print array
content to screen.
• Idea
– Print the value of each element of the array from index 0
to n-1.
0 1 2 n-1 MAX - 1
… … …
21
Display array
printf(“\n”);
}
22
Search for an element in the array
• Requirements
– Find out if element x is in an array of size n? If it does
appear, print the location of its first occurrence..
• Idea
– Consider each element of the array a. If the element is
equal to x then return that position. If not found, return -
1.
x position = 1
0 1 2 n-1 MAX - 1
a x b … x … …
23
Search for an element in the array
if (pos < n)
return pos;
else
return -1;
}
24
Search for an element in the array
return -1;
}
25
Check properties of arrays
• Requirement
– Given an array a and the number of elements n, check a
is a prime array?
• Idea
– Method 1: Counts the number of prime numbers of the
array. If this number equals exactly n then the array is a
prime array.
– Method 2: Counts the number of non-prime numbers of
the array. If this number equals exactly 0 then the array
is a prime array.
– Method 3: Find out if there are any non-prime elements.
If this element exists, the array is not all prime.
26
Preparation
• Pre-defined functions
– int isPrime(int n): check whether a number is
prime. Returns 1 if n is a prime number,
otherwise returns 0.
int isPrime(int n)
{
int i, count = 0;
for (i = 1; i <= n; i++)
if (n%i == 0)
count++;
if (count == 2)
return 1;
else return 0;
}
27
Check properties of arrays
if (count == n)
return 1;
return 0;
}
28
Check properties of arrays
if (count == 0)
return 1;
return 0;
}
29
Check properties of arrays
return 1;
}
30
Extract elements satisfies the condition
• Requirement
– Given an array a and the number of elements n, extract
the primes in the array a into array b.
• Idea
– Traverse through each element of array a, if it is a prime
number then put in array b.
31
Extract elements satisfies the condition
32
Splitting array
• Requirement
– Given array a and the number of elements na, split array
a into 2 arrays b (containing prime numbers) and array c
(the remaining numbers).
• Idea
– Method 1: write a function that separates prime numbers
from array a into array b and another function that
separates non-prime numbers from array a to array c.
– Method 2: traverse through each element of array a, if it
is a prime number then put in array b, otherwise put in
array c.
33
Splitting array
35
Merge arrays into an array
36
Find the maximum value of the array
• Requirement
– Given an array of n elements, find the maximum value in
the array (called max)
• Idea
– Assume the current max value is the first element value
a[0]
– In turn, check the remaining elements for updates max.
max 8
7
?
0 1 2 n–1 MAX - 1
7 2 8 … 8 … …
37
Find the maximum value of the array
return max;
}
38
Sort array into ascending
• Requirement
– Given an array of size n, arrange the array a in
ascending order.
• Idea
– Use 2 variables i and j to compare all pairs of elements
together and swap them if they in the wrong order.
tempt 5
8
0 1 2 n–1 MAX - 1
5
1 1
5 8
6 … 6
8 … …
39
i j j j j
Preparation
• Pre-defined functions
– void Swap(int &x, int &y): swap 2 integer
numbers
40
Sort array into ascending
41
Add an element to the array
• Requirement
– Add the element x to an array a size n at position pos.
• Idea
– "Push" the elements starting at pos to the right.
– Put x in position pos in the array.
– Increase n by 1.
x insert?
0 1 2 3 n–1 n MAX - 1
a b c … z … …
42
pos
Add an element to the array
a[pos] = x;
n++;
}
}
43
Delete an element in the array
• Requirement
– Delete an element in array a at position pos.
• Idea
– "Drag" the elements to the right of the position pos to the
left by one position.
– Decrease n by 1.
delete?
a x b … z … …
44
pos
Delete an element in the array
n--;
}
}
45
Exercies
1. Write a function to check if a given array meets
the following conditions:
a. Array is an even array
b. Array is an incremental array
46
Exercies
2. Write functions to perform the following
calculations:
a. How many numbers in array are divisible by 4
but not divisible by 5?
b. Sum of primes in the array
3. Write functions that performs the search
operations
a. The last position of the x element in the array
b. Position the first prime number in the array
c. Find the smallest number in the array
d. Find the smallest positive number in the array
47
Exercies
4. Write functions that perform operations:
a. Extract the primes in array a into array b.
b. Split array a into 2 arrays b (containing positive
integers) and c (containing the remaining
numbers)
c. Sort array into descending
d. Arrange the array so that the positive numbers
leading to the array decrease, followed by
increasing negative numbers, followed by
zeros.
48
Exercies
5. Operations to add / delete / update
elements:
a. Change the primes in the array to the number 0
b. Insert the number 0 behind the prime numbers
in the array
c. Delete all prime numbers in the array
49
Content
• One-dimensional array
• Two-dimensional array
50
Matrix
0 1 … n-1 0 … n-1
0 0
Am,n An
…
…
m-1 n-1
51
Matrix
0 0 0
An
…
…
n-1 n-1 n-1
0 0 0
An
…
…
n-1 n-1 n-1
row + column = n-1 row + column > n-1 row + column < n-1
52
Matrix in a program
• Consider the program:
– Enter a matrix of 5 x 10 integers, then print it
out.
▪ Declare 5 arrays: int a1[10], a2[10], a3[10], a4[10],
a5[10].
– Enter a matrix of 50 x 10 integers, then print it
out.
▪ Declare 50 arrays! This quickly becomes impractical.
➔ How to declare a matrix of M x N?
53
Matrix in a program
• Method 1:
– Use array 1-D with:
▪ Matrix M x N ~ array 1-D of M x N elements.
▪ Matrix [ row i, column j ] ~ array [ i * N + j ].
– Complex!
Matrix Array 1-D
0 0 0 0 0 0 0 0 1 1 1 1 2 2 2 2 …
1 1 1 1
2 2 2 2
…
54
Matrix in a program
• Method 2:
– Use array 2-D.
0 1 2 3
Matrix 1
55
Declaration
• Syntax
typedef <data_type> <array_name>[<N1>][<N2>];
0 1 2 3
0
Matrix 1
2
56
Declaration
• Syntax
– Directly
<data_type> <array_name>[<N1>][<N2>];
– Indirectly
<array_type> <array_name>;
<array_type> <array_name_1>, <array_name_2>;
57
Declaration
• Example
– Direct
int a[10][20], b[10][20];
int c[5][10];
int d[10][20];
– Indirectly
Matrix10x20 a, b;
Matrix11x11 c;
Matrix10x20 d;
58
Initialization
• Initialization:
<data type> <array name>[<rows>] [<columns>] =
{
<Initialize row 0>,
<Initialize row 1>,
…
};
// Initialize all elements. // Initialize some elements. // Initialize with auto rows.
int m1[ 3 ][ 5 ] = int m1[ 3][ 5 ] = int m1[ ][ 5 ] =
{ { {
{ 1, 1, 1, 1, 1 }, { 1, 1 }, { 1, 1 },
{ 1, 2, 3, 4, 5 }, { 1, 2, 3 }, { 1, 2, 3 },
{ 5, 4, 3, 2, 1 } {0} {0}
}; }; };
59
Access in Two-Dimensional Array
• By index
<array_name>[<index1>][<index2>]
• Example 0 1 2 3
0
– The two-dimensional array
1
int a[3][4];
2
– Access an element
▪ Valid: a[0][0], a[0][1], …, a[2][2], a[2][3]
▪ Invalid: a[-1][0], a[2][4], a[3][3]
60
Working with 2-D array
• Operations:
– Step 1: Iterate through array.
▪ Use 2 nested loops.
– Outer loop: iterate through rows.
– Inner loop: iterate through columns in each row.
61
Assign value in array
• Ordinary assignment cannot be used, but must be
assigned directly to each element in a two-
dimensional array
<dest_array> = <source_array>; //wrong
<dest_array>[<index1>][index2] = <value>;
• Example
int a[5][10], b[5][10];
b = a; // wrong
int i, j;
for (i = 0; i < 5; i++)
for (j = 0; j < 10; j++)
b[i][j] = a[i][j];
62
Pass the array to the function
• Pass the array to the function
– The array type parameters in the function
declaration are the same as declaring the array
variable.
void EnterMatrix(int a[50][100]);
• Function call
65
Some conventions
• Maximum size
#define MAXD 50
#define MAXC 100
66
Enter the Matrix
• Requirement
– Allows entering array a with m rows, n columns
• Idea
– Given a 2-dimensional array in which the maximum
number of rows is MAXD, the maximum number of
columns is MAXC.
– Enter the number of elements actually using m, n of
each dimension.
– Enter each element from [0] [0] to [m-1] [n-1].
67
Enter the Matrix
int i, j;
for (i=0; i<m; i++)
for (j=0; j<n; j++)
{
printf(“Enter a[%d][%d]: ”, i, j);
scanf(“%d”, &a[i][j]);
}
}
68
Output Matrix
• Requirement
– Allows printing array a with m rows, n columns
• Idea
– Prints the value of each element of a 2-dimensional
array from row 0 to row m-1, each row outputs the value
of column 0 to column n-1 on that row..
69
Output Matrix
printf(“\n”);
}
}
70
Searches for an element in the array
• Requirement
– Finds if the element x is in a matrix of size mxn?
• Idea
– Traverse each element of the matrix a. If the element is
x, it returns true (1), otherwise false (0) is returned.
71
Searche for an element in the array
72
Sum the elements in the matrix
• Requirement
– Given matrix a, size mxn. Sum the elements located in:
▪ Row d, column c
▪ Primary diagonal, secondary diagonal (square matrix)
▪ The upper / lower half of the primary diagonal (square matrix)
▪ The upper / lower half of the secondary diagonal (square matrix)
• Idea
– Traverse the matrix and add up the elements with the
desired coordinates.
77
Sum the elements on the row
sum = 0;
return sum;
}
78
Sum the elements on the column
sum = 0;
return sum;
}
79
Sum the primary diagonal
sum = 0;
return sum;
}
80
Sum the secondary diagonal
sum = 0;
return sum;
}
81
Sum the elements above the primary diagonal
sum = 0;
return sum;
}
82
Sum the elements above the secondary diagonal
sum = 0;
return sum;
}
83
Find the maximum value of the Matrix
• Requirement
– Given matrix a, size mxn. Find the maximum value in
the matrix a
• Idea
– Assume the current max value is the first element value
a[0] [0]
– In turn, check the remaining elements for updating max.
84
Find the maximum value of the Matrix
max = a[0][0];
return max;
}
85
Exercises
Write C/C++ program (organize in functions and multiple-
file project):
- Enter an array of integers.
- Count:
a) Negative numbers in the array.
b) Prime numbers in the array.
Input format:
Enter N = 3
Element 0 = 2
Element 1 = 3
Element 2 = -6
Output format:
Negative numbers: 1.
Prime numbers: 2.
86
Exercises
Write C/C++ program to check array:
(organize in functions and multiple-file project)
- Enter a array of integers.
- Check if:
a) Array is in ascending order.
b) Array is symmetric.
c) Array is an arithmetic progression.
Output format:
Array <is/is not> ascending.
Array <is/is not> symmetric.
Array <is/is not> a arithmetic progression.
87
Exercises
Write C/C++ program to operate on students:
(organize in functions and multiple-file project):
- Declare struct to represent a student (stated
in the lesson).
- Enter a list of N students.
- Print a list of excellent students (GPA >= 8.5)
in descending order of GPA.
88
Exercises
Write C/C++ program to operate on date:
(organize in functions and multiple-file project):
- Declare struct to represent date (day, month,
year).
- Enter a list of date.
- Print the list from the latest date to the oldest
one
89
Exercise
Write C/C++ program as follow:
(organize in functions and multiple-file project)
- Enter square matrix N x N of integers.
- Print to screen:
a) Sum of elements on each diagonal.
b) Row index having max sum of elements.
c) It is a magic square or not.
Output format:
Main diagonal = <sum of elements>.
Anti-diagonal = <sum of elements>.
It <is/is not> a magic square.
90
Exercise
Write C/C++ program to manipulate matrix:
(organize in functions and multiple-file project)
- Enter a matrix M x N of integers.
- Print to screen all elements satisfying its
value equals to sum of the remaining elements on
its row and column.
91
Exercise
Write C/C++ program to rotate matrix:
(organize in functions and multiple-file project)
- Enter a matrix M x N of integers.
- Rotate left matrix 90 degree and print result.
- Rotate right matrix 90 degree and print result.
92
The End