Lecture 6: Arrays and
Structures
Harbin Institute of Technology ( Shenzhen )
School of Computer Science and Technology
Zhang Meishan (mason.zms@gmail.com)
Copyright : Harbin Institute of Technology , Su Xiaohong , sxh@hit.edu.cn
Overview
• Arrays
• Structures
• Enumerated data types
• Sort
• Find
6.1 Arrays
• Array : a group of variables of the same data type
• Define
• Store
• Dimension of the array: the number of elements in an array
• Array index (or subscript) :The position of an element in an array
The index of the array numbers starts with 0
6.1 Arrays
• Array
• How to refer to a particular element ?
• use the array name and the index in brackets
52
• How to access the last element?
√ or × ?
6.1 Arrays
• Program Example
• define ages as an array of 10 integers
• format:
•The for loop is used to read each element of the
array and add them to total_age.
6.1 Arrays
• Program Example: find the minimum and maximum values in an array
•definea constant integer SIZE and an array
“ages” with size SIZE
symbolic constant
•The const keyword is used in the definition to
specify that its value cannot be changed.
• The identifier is usually written in uppercase.
•Usinga symbolic constant makes the program easier
to modify.
6.1 Arrays
• Program Example
•The for loop reads in values into the array
ages and totals them up.
•The for loop compares each element in the array
with the values youngest and oldest.
‐ Whenages[i] larger than oldest, its value is
assigned to oldest.
‐ Whenages[i] less than youngest , its value is
assigned to youngest .
•The smallest element of the array is in youngest and
the largest is in oldest when the loop is completed.
6.1 Arrays
• Initializing an array
• Define and initialize an array days.
•The initial values in the array are separated
by , and placed between { }.
6.1 Arrays
• Initializing an array
• When the list of initial values is less than the number of elements in
the array, the remaining elements are initialized to 0.
• If an array is defined without specifying the number of elements
and is initialized to a series of values, the number of elements in the
array is taken to be the same as the number of initial values.
||
6.1 Arrays
• Two-dimensional arrays
• A two-dimensional array has more than one row of elements
6.1 Arrays
• Two-dimensional arrays
• Define: enclose each dimension of the array
in brackets
• Access an element: specify the row and the
column
• The row number starts at 0 and ends at 6
• The column number starts at 0 and ends at
4.
6.1 Arrays
• Program Example: reads in the number of students using the five laboratories
over seven days
• Symbolic constant NO_OF_DAYS and
NO_OF_LABS.
• Define a two-dimensional array usage with
NO_OF_DAYS rows and NO_OF_LABS
columns.
6.1 Arrays
• Program Example
•The for loop reads in values into the
array usage[][].
•The for loop totals every column
of array usage and average them.
6.1 Arrays
• Initializing a two-dimensional array
• Initialized by enclosing the initial values in braces
• Place the initial values of each row on a separate line or add
braces in each row to improve readability
6.1 Arrays
• Initializing a two-dimensional array
• Omit the first dimension
• Compiler will calculate the number of rows
• Missing values are initialized to 0
Note that the first
dimension is required
here, why?
6.1 Arrays
• Multi-dimensional arrays
• Define arrays with any number of dimensions
• The elements of this array are accessed by using three subscripts
6.2 Structures
• Arrays are suitable for storing sets of homogeneous data
• For example, a student’s test scores
• For items of information that are logically related but each
item may have a different data type?
• A student’s number and test scores
• Logically related items of information that may have different
data types can be combined into a structure
6.2 Structures
• Declaring a structure
• Step1 : Declare a structure template:
• structure tag: name of the structure
• structure member: each item in a structure
• A structure
template consists of the
reserved keyword struct followed by the
name of the structure.
6.2 Structures
• Declaring a structure
• Step 2 : define variables with the type declared
define student1 and
student2 to be of the
type struct student_rec
6.2 Structures
• Program Example
6.2 Structures
• Program Example
6.2 Structures
• Declaring a structure
• Access members of a structure variable: with the member selection
operator “.”
6.2 Structures
• Another declaration form of a structure
6.2 Structures
• Initializing a structure variable
• Place their initial values in braces to initialize a structure
6.2 Structures
• Nested structures
• A structure that contains another structure as one of its
members.
6.2 Structures
• typedef allows to define a synonym for a built-in or a
programmer defined data type
• Use typedef to define a synonym DATE for struct date:
6.2 Structures
• Example: Define a five-element array persons.
• Each element of this array is of the type struct personnel with
members number, dob and joined
• The members dob and joined are themselves structures and have
members day, month and year.
• Which member will be accessed ?
• persons[0].number ?
• persons[4].joined.year ?
6.3 Enumerated data types
• An enumerated data type is used to describe a set of integer
values.
•The names enclosed in { and }
•Name of the enumerated must be integer constants
data type defined • The value of no is 0; the value of
•response
is called the yes is 1; the value of none is 2….
enumeration tag
• These statements declare the data type response to have one of
three possible values: no, yes, or none.
• answer is defined as an enumerated variable of type response.
6.3 Enumerated data types
• Another definition form
• when the enumerated data type and the enumerated variables
are defined together, the enumeration tag is optional
• Arrays of enumerated data type
• Values other than 0, 1, and 2 can also be used
6.4 Sort
• Sorting algorithm
-- Sorting by exchange
-- Sorting by selection
6.4 Sort
"Sorting by exchange," also known as "Bubble Sort," can be described in a few steps:
1.Step One: Comparing Adjacent Elements
•Start from the beginning of the list and compare each pair of adjacent elements.
2.Step Two: Swapping Positions
•If the preceding element is greater than (or equal to) the succeeding element, swap
their positions. This ensures that the larger element moves towards the end of the list.
3.Step Three: Repeat Until Sorted
•Repeat steps one and two until all elements in the list are arranged in ascending (or
descending, depending on the implementation) order.
The core idea of this algorithm is to continually compare adjacent elements and swap their
positions if necessary until the entire list is sorted.
6.4 Sort
• Sort by exchange :
Sorting a one-dimensional array storing student grades.
6.4 Sort
Do a two-number swap:
6.4 Sort
Sorting by selection is a straightforward sorting algorithm that sorts an array by repeatedly
finding the minimum element from the unsorted part and moving it to the beginning.
1.Step One: Iterate through the array to find the minimum element.
2.Step Two: Swap the minimum element with the first element of the unsorted part.
3.Step Three: Move the boundary of the unsorted part one element to the right.
4.Step Four : Repeat steps 1-3 until the entire array is sorted.
This process continues until all elements are sorted, with each iteration reducing the size of
the unsorted portion of the array by one element.
6.4 Sort
• Sort by selection :
Sorting a one-dimensional array storing student grades.
6.4 Sort
• Sort by selection :
6.5 Find
• Searching algorithm
-- Linear search
-- search in half
6.5 Find
Sequential search, also called linear search, involves scanning through each element in a list
until finding the target element or reaching the end. It's a simple method for locating elements
in an array.
1.Start: Begin at the first element of the list.
2.Comparison: Compare the target element with the current element being examined.
3.Check: If the current element matches the target element, the search is complete, and the
index of the element is returned.
4.Continue or Terminate: If the current element does not match the target element, move to
the next element in the list. Repeat the comparison process until either the target element is
found or the end of the list is reached.
5.End: If the target element is not found in the list, return a message indicating that the
element is not present.
6.5 Find
• Linear search:
Don’t have to
sort beforehand
6.5 Find
Search in Half , also called Binary Search. Searching in half divides the search space in two and
identifies the containing half of the desired item. Here are the steps:
1.Initialize: Start with a sorted list.
2.Divide and Compare: Check the midpoint of the list against the target.
3.Narrow Down: Based on the comparison, discard half of the list each time.
4.Repeat: Keep dividing and comparing until the target is found or the search space is empty.
5.Result: Return the index if found, otherwise indicate absence.
6.5 Find
• Binary search :
should be sorted
Number to find
Not found
6.5 Find
Search value x = 28
x >num[mid] low = mid+1
x = num[mid] Find
Array 0 1 2 3 4
subscripts
First Loop 22 24 26 28 30
low mid high
Second Loop 22 24 26 28 30
low(mid) high
6.5 Find
Search value x = 27
x >num[mid] low = mid+1
x < num[mid] high = mid - 1
Array 0 1 2 3 4
subscripts
First Loop 22 24 26 28 30
low mid high
Second Loop 22 24 26 28 30
low(mid) high
Third Loop 22 24 26 28 30
high low
Now, low < high .Loop ended ,not found
Q&A
ZhangMei
Shan
44/37
Homework
• 1. Write statements to define each of the following:
(a) a one-dimensional array of floating-point numbers with ten
elements
(b) a one-dimensional array of characters with five elements
(c) a two-dimensional array of integers with seven rows and eight
columns
(d) a 10 by 5 two-dimensional array of double precision numbers
(e) a 10 by 8 by 15 three-dimensional array of integers.
Homework
• 2. In a magic square the rows, columns and diagonals all
have the same sum. For example:
Write a program to read in a two-dimensional integer
array and check if it is a magic square.
Homework
• 3. Given the following definitions,
write statements to
(a) assign a value to each member of stock_item
(b) input a value to each member of stock_item
(c) display the value of each member of stock_item
Homework
• 4. Create an enumerated data type for each of the following:
(a) the days of the week: Monday, Tuesday, Wednesday, and so on
(b) the months of the year
(e) the points on a compass.
Homework
• 5. Given the array [22, 3, 1, 9, 6, 12, 8], provide the
sorting results for each round of selection sort. For
example, given the array [3, 2, 1], the sorting results for
first round is [1, 2, 3].