Programming With Arrays - Grade 8

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Programming with Arrays

What is a an Array?

● An array is a collection of elements, each identified by an index or a key.


● All elements in an array must be of the same data type (e.g., integers, strings,
or objects).
Example of an array:
Numbers = [23,56,45,89,12]
The name of the above array is Numbers
It stores the elements of Integer data type
The size of the array is 5
Declaring an array

An array is declared by giving the name, size and type of data it holds
Declaration of Array:
DECLARE name_of_athe_array : ARRAY[size_of_the_array] OF DATATYPE
Example:
Declaring an array called Names that stores names of 10 students
DECLARE Names : ARRAY[10] OF STRING
What is a List in Python?
● List is a sequence of values called items or elements
● The elements can be of any data type
● Creating a list is as simple as putting different comma-separated values
between square brackets.
For example −
Subjects = ['physics', 'chemistry', ‘Biology’]
Subjects is a list that contains three elements
Marks = [56,90,45,56.67,34,89.8]
Marks is a list that contains 6 elements
Using Lists you can store values and retrieve them anywhere in
your program
Accessing elements inside an array
Elements inside an array can be accessed using their index
Index is the position of an element inside an array
We use the square brackets [ ] with the index inside to obtain value available at that
index.
Index always starts from 0 and ends at n-1 - n being the size of the list
Example:
Consider the following list
Subjects = [‘Physics’ , ‘Chemistry’, ‘Computer Science’ , “Mathematics’ , ‘Biology’]
Index - 0 1 2 3 4

To access Mathematics we use - Subjects[3]


To access Chemistry we use - Subjects[1]
Some more examples
Consider the following array:

Marks = [23, 45, 67, 89, 34, 78, 12, 100]

To print marks of the fourth student, we write - print(Marks[3])

To print marks of the first student, we write - print(Marks[0])

To print marks of the last students, we write - print(Marks[7])


Pseudocode to create a new array
DECLARE Marks : ARRAY[10] OF INTEGER
i←0
WHILE i<10:
M = int(input(“enter marks obtained by the student”))
Marks[i] = M
i←i+1
print(“the array is:” , Marks)
Creating a new list
Append Function:
Append function is used to add elements to a list
Example:
Write a program to input marks obtained by 10 students and store them in a
list
Marks = [ ]
for i in range(0,10):
M = int(input(“enter marks obtained by the student”))
Marks.append(M)
print(“the list is:” , Marks)

You might also like