Topic8 Array Part1
Topic8 Array Part1
programming
Topic 8- Array
int marks[5]; char animals[4][20];
1
Outline
❑ An overview of the lessons
▪Introduction
▪ Problem when not using array
▪Array
▪ What is array?
▪ How to use array?
▪ More on array
2
Introduction
❑ Problem
▪ Problem #1: Suppose we want to get 100 students’ names then display theirs
names in a list. Will you use 100 variables? Disadvantages:
Too many creation of variables?
Var name1, name2, ..., name100 : Sequence of characters What if we have more than 100
Begin variables?
read(name1, name2, ..., name100)
End
▪ Problem #2: Suppose we want to get 100 subjects’ scores of a students then
do summation of those score.
Var score1, score2, …, score100, sum : float
Will we need 100 Begin
variables to store read(score1, score2, ..., score100)
those scores? sum score 1+ score2 + … + score100
3
End
Array
❑ What is an array?
▪ Array is a kind of data structure that stores many variables (elements) as a
single special variable.
▪ Each variable in an array is called an array element and they have the same
variable type
▪ You could have an array of integers or an array of characters or an array of
anything that has a defined data type.
Array
▪ An overview of an array:
element
Index or position
4
Array
❑ Declaring (creating) an array
▪ To declare an array, we have to choose
▪ Type of element in the array
▪ Number of elements in the array
▪ Syntax
Var identifier[number of elements] : Type of element in array
Suppose that we add values (10, 20, .., 100) to the array.
▪ Examples: Creating array The array now look like this:
Var num[20] : Integer
Var scores[10] : Float
Var name[50] : Array/sequence of characters
Var s[5][100] : Array of string (5 elements) 5
Array
❑ Index or position
▪ In array, the value of index is
▪ Start from 0 (some language may start with index 1)
▪ E.g: In C language, index starts from 0 but in Matlab index starts from 1
▪ Integer number
▪ Last value of index is equal to number of elements in array minus 1
(when its index starts with 0)
•
•
•
Array
❑ Using array to solve the previous problems?
▪ Solution for Problem #1:
▪ Use an array with the size of 100 and its type is a string (sequence of characters)
10
Example 2: Array example with initialization values
11
Assignment Deadline: 1 week
❑ Practice exercises
12
Assignment Deadline: 1 week
=>OUTPUT: Average is: 105. Scores that are more than average are: 110, 120,
130,140,150,160,170,180,190,200 Coding hour
13
Assignment Deadline: 1 week
4-The same to exercise #1. We also would like to count a total number of
duplicate elements and non-duplicate elements in the array.
5-The same to exercise #1. In addition, we also want to print all unique
elements in an array
14