Arrays and Linear Search
Arrays and Linear Search
N. B. One index is required for accessing an element of a 1D array whereas two indices are required for
accessing an element of a 2D array.
Representation of an array in pseudocode is always with the name of the array followed by index / indices
inside the square bracket [ ]. For example, a 1D array, Name[10] means that 10th element of the Name array
has been accessed. An example of a 2D array, Mark[5, 2] means that the element in the 5th row and 2nd
column of the Mark array has been accessed.
N.B. For accessing an element of a 2D array, the row index has to be given first and then the column index
Page 1 of 17
within a square bracket [ ] separated by a comma (,). That means the format to access a 2D array is always
as follows: ArrayName[Row, Column].
For example, if two-dimensional array, Mark has 10 rows and 5 columns then the indices are as follows:
Mark[1, 1], Mark[1, 2], Mark[1, 3], Mark[1, 4], Mark[1, 5] //For first row
Mark[2, 1], Mark[2, 2], Mark[2, 3], Mark[2, 4], Mark[2, 5] //For second row
and so on and so forth
Declaring Arrays:
• When an array is declared, the computer sets aside memory to store the values of the elements of
the array.
• Declaring an array means telling the computer what is the data type of the array and how many
elements will be stored in it. But declaration does not mean that any value has been assigned to it
automatically.
Here Lowerbound and Upperbound are technical terms for the minimum and maximum values for an array
subscript. Lowerbound indicates the start index of the array and Upperbound indicates the last index of the
array. They will be separated by colon ( : ). Both the values are inclusive. This represents the size of the
array which actually means the number of elements the array can hold.
The above pseudocode statement declares an array with 5 elements, all of which must be of REAL data type
values.
The following illustration shows an array named Weight has 5 elements in it.
N.B. The first element of an array can have subscript/index as 0 or 1. But if not mentioned otherwise, then
always start with index 1.
The previous declaration could have been made in the following way also
In this case the starting index is 0. So the first element of the 1D array would be Weight[0] which would
have 50.25 as a value in it. This array would also be able to hold 5 elements in it. But it is not recommended
to give start index 0 unless it is mentioned in the question.
Some example statements that can be performed in a one-dimensional array, Weight is given below. The
starting index here is 1.
- OUTPUT Weight[3] //This will display 35.75 on the screen
Page 2 of 17
- Weight[2] ← Weight[2] + 10.0 //Weight[2] had a value 85.0. This will be added with 10.0 and will
update Weight[2] with a value 95.0. That means previous value of 85.0 has been overwritten
- INPUT Weight[1] // This will take a new input and assign it in index 1 which will overwrite the
previous value of 50.25
- Weight[5] ← 45.5 // This will assign a new value to Weight[5] overwriting previous value of 39.0
- Weight[3] ← Weight[4] * 2 //This will update the value of Weight[3] with 44.0 as Weight[4] had a
value 22.0 and will be multiplied by 2
The above pseudocode statement declares an array with 5 rows and 3 columns, all of which are of data type
CHAR and it can store 15 elements in total. The starting index for both the rows and columns are 1. For
example, the array has been used to store the following letters in it.
1 2 3
1 A N C
2 C M I
3 E F L
4 P G P
5 Q T W
Since a 2D array is made up of rows and columns that is why to access an element the row number followed
by the column number is required to make the index. This means that two indices are required to access any
element for a 2D array.
The previous declaration could have been made in the following way also
In this case the starting index is 0 for both the rows and columns. So the first element of the 2D array would
be Grade[0, 0] which would have ‘A’ as a value in it. This array would also be able to hold 15 elements in it.
One thing to remember, the start index for the rows and columns cannot be a mixed up of 0 and 1. It has to
be either 0 for both rows and columns or 1 for both rows and columns.
Page 3 of 17
Assigning values to a one-dimensional array:
Problem: A one-dimensional array, Days need to be assigned values such as Sunday, Monday up to
Saturday in consecutive index. Write down the pseudocode for this. You need to declare the array.
Initializing the same value to all elements in a one-dimensional array: Write down the pseudocode to
declare and initialize a 1D array with 0 for each element which can hold 50 whole numbers in it. Declare all
the data structures before use.
FOR Index ← 1 TO 50
Num[Index] ← 0
NEXT Index
Explanation: The loop will start from 1 as its first value for the control variable Index. It will go inside the
loop and execute the one statement that is given. The array, Num will have its index value as 1 now. So, in
Num[1] position, 0 will be assigned. Then the Index value will be incremented to 2 and the same process
will continue 50 times. So, each time, the control variable value will be incremented and since this variable
has been used as an index of the array that is why in each iteration of the loop, 0 will be assigned to each
element of the array one by one.
N.B. The control variable in a loop which will be used as an index for an array must be of INTEGER data
type
Data type: Data type for an array can be any one of INTEGER, REAL, STRING, CHAR or BOOLEAN
Remember that to manipulate 1D array we usually need to use loop. Since it is a fixed number of iterations
required that is why FOR…TO…NEXT loop is most preferred. The control variable of the loop will be used
as index value for the array.
Initializing the same value to all elements in a two-dimensional array: Write down the pseudocode that
will initialize each element of a 2D array to 0.0. The name of the array is “Number” and the array is made up
of 20 rows and 5 columns which can hold whole numbers as well as decimal numbers. The starting index is
0. You need to declare all the data structures before use.
Page 4 of 17
FOR Row ← 0 TO 19 //Outer loop for rows
FOR Column ← 0 TO 4 //Inner loop for columns
Number[Row, Column] ← 0.0 //0.0 has been given because the array has been declared as REAL
//data type
NEXT Column
NEXT Row
Explanation: We usually use nested loop (a loop inside another loop) to manipulate a 2D array. In most
cases we need to access all the columns in turn for each row. So, we need to set an outer loop for the number
of rows and an inner loop for the number of columns. For every iteration of the outer loop for each row, the
entire cycle of the inner loop for the columns will be completed. Since both the loops are of fixed number of
times that is why FOR...TO...NEXT loop is the recommended loop to be used for 2D arrays also.
FOR Count ← 1 TO 30
OUTPUT “Enter student name for student ”, Count, “: ” These two statements can be written as
INPUT SName one instruction as below:
StudentName[Count] ← SName INPUT StudentName[Count]
OUTPUT “Enter student weight for student ”, Count, “: ”
INPUT SWeight These two statements can be written as
one instruction as below:
StudentWeight[Count] ← SWeight
INPUT StudentWeight[Count]
NEXT Count
Note that the Name and Weight of First Student corresponds to the element StudentName[1] and
StudentWeight[1] respectively and the Name and Weight of Thirtieth Student correspond to the element
StudentName[30] and StudentWeight[30] respectively.
When multiple arrays will be used to represent a scenario, then values of the different arrays will be stored
using the same corresponding index.
Explanation: In the above example, two separate variables have been used to hold values temporarily and
then assign the values to the array indices. This could have been done using direct array indices also. The
control variable Count will start with the value 1 and will continue as long as the value is less than or equal
to 30. So, after taking input of the first student’s name in the variable SName it will assign the value to index
1 of StudentName array. Then it will ask for student weight and the value will be stored in SWeight variable
and then from there it assigns the value to index 1 of StudentWeight array. Then the control variable Count
will be incremented to 2 and the same process will continue for 30 times in total one by one.
Page 5 of 17
Displaying values from multiple one-dimensional arrays together:
Here is how to display (output) 30 values from each of the two arrays using loop (which were stored in
previous section). The values represent Names of 30 students in one array and Weights of 30 students in
another array.
FOR X ← 1 TO 30
OUTPUT “Information of student ”, X, “ is as follows: ”
OUTPUT “Student Name: ”, StudentName[X]
OUTPUT “Student Weight: ”, StudentWeight[X]
The above three statements could be combined into one statement as below:
OUTPUT “Student ”, X, “ Name: ”, StudentName[X], “ and weight: ”, StudentWeight[X]
NEXT X
Explanation: Using one loop, we can access multiple different arrays if the values in different arrays are
stored using the same index as the data were stored using the same index in different arrays.
Explanation: The outer loop will start execution with the value 1 of its control variable and will go inside
the loop. This outer loop will continue 30 times. When the outer loop has value 1 of its control variable then
the inner loop will start its execution with value 1 of its control variable and will continue its entire cycle as
long as it is less than or equal to 5. The input values will be stored in the 2D array one by one by
incrementing the control variable of the inner loop. That means in the first iteration of the outer loop the
array index will be as follows: StudentMark[1,1], StudentMark[1,2], StudentMark[1,3], StudentMark[1,4]
and StudentMark[1,5]. Then the outer loop control variable will be incremented to 2 and the inner loop
again will start from 1 and continue till 5. So, the array index will be as follows: StudentMark[2,1],
StudentMark[2,2], StudentMark[2,3], StudentMark[2,4] and StudentMark[2,5]. The process continues the
same way and values are stored inside the array indices one by one for all the 30 students.
Problem: Write down the pseudocode that has height of 50 students stored in a one-dimensional array,
Height. Find the average height of the students and display the result. You need to declare all the data
structures before use.
//Declaration of the array is not required because it has already been used
DECLARE Total, Average : REAL
DECLARE Index : INTEGER
Total ← 0.0
FOR Index ← 1 TO 50
Total ← Total + Height[Index] //Totaling is performed with value of each index of the array in turn
NEXT Index
Average ← Total / 50
OUTPUT “Average height of the students is: ”, Average
Problem: A teacher wants to record names of students and the marks that each student has achieved in her
subject. The class has 50 students in it.
She wants to write a program that will
- Take input of names of all the students in a one-dimensional array, StudentNames
- Take input of the marks for each student in another one-dimensional array, StudentMarks
- Each mark is between 0 and 100 inclusive. This has to be ensured by the program that any invalid
mark is rejected and only mark between the range is accepted
Write down the algorithm in pseudocode for the above scenario. All the data structures that you need must
be declared before use.
Solution 1:
DECLARE StudentNames : ARRAY[1:50] OF STRING
DECLARE StudentMarks : ARRAY[1:50] OF INTEGER
DECLARE Mark, Index : INTEGER
FOR Index ← 1 TO 50
OUTPUT “Enter name of student: ”, Index, “: ”
INPUT StudentNames[Index]
OUTPUT “Enter mark of student: ”, StudentNames[Index], “: ”
INPUT Mark //A temporary variable has been used
WHILE Mark < 0 OR Mark > 100 DO //This loop is being used for validation
OUTPUT “Invalid mark. Re-enter”
INPUT Mark
ENDWHILE
StudentMarks[Index] ← Mark //A valid mark which is being held in variable Mark has been assigned
//to the array index after passing the validation rule
Page 7 of 17
NEXT Index
//If a value requires to be validated while input being taken for an array then a separate variable
should be used for validation and then once the validation rule passes, the value should be assigned to
the array index.
Solution 2:
DECLARE StudentNames : ARRAY[1:50] OF STRING
DECLARE StudentMarks : ARRAY[1:50] OF INTEGER
DECLARE Index : INTEGER
FOR Index ← 1 TO 50
OUTPUT “Enter name of student: ”, Index, “: ”
INPUT StudentNames[Index]
REPEAT //This loop is being used for validation
OUTPUT “Enter mark of student: ”, StudentNames[Index], “: ”
INPUT StudentMarks[Index] //The array index being directly used instead of a temporary variable
IF StudentMarks[Index] < 0 OR StudentMarks[Index] > 100
THEN
OUTPUT “Invalid mark. Re-enter”
ENDIF
UNTIL StudentMarks[Index]>=0 AND StudentMarks[Index]<=100
NEXT Index
Problem: Temperature of a month (30 days) has already been stored in a two-dimensional array. For each
day the temperature was taken for every hour (24 hours) where the day represents the row and hours
represent the column. Find the average temperature for each day and also the average temperature for 30
days. Display the average for each day and also for the entire month. The name of the array is Temperature.
Write down the pseudocode for the above scenario. You need to declare all the data structures before use.
MonthTotalAverage ← 0.0 //This variable will be used to do the totaling for the entire month
FOR Day ← 1 TO 30 //Outer loop for days
DayTotal ← 0.0 //Needs to reset 0.0 for each day
FOR Hour ← 1 TO 24 //Inner loop for hours
DayTotal ← DayTotal + Temperature[Day, Hour] //Totaling being done for 24 hours in turn
NEXT Hour
AverageEachDay ← DayTotal / 24 //Finding the average of each day
OUTPUT “The average for day ”, Day, “is ”, AverageEachDay
MonthTotalAverage ← MonthTotalAverage + AverageEachDay //Totaling for average being done for
//30 days in turn
NEXT Day
MonthAverage ← MonthTotalAverage / 30
OUTPUT “The average temperature for all 30 days is ”, MonthAverage
Problem: A two-dimensional array, Marks already has subject marks stored for 50 students. Each student
Page 8 of 17
takes 5 subjects. The column represents the subjects. Find the average of each student separately and then
find the average of all the students together. Display the average results. Write down the pseudocode for the
above scenario.
TotalAverage ← 0.0 //This variable will be used to do the totaling of average for the entire month
FOR Student ← 1 TO 50 //Outer loop for Row
IndividualTotal ← 0 //Needs to reset 0 for each student
FOR Subject ← 1 TO 5 //Inner loop for Column
IndividualTotal ← IndividualTotal + Marks[Student, Subject] //Totaling being done for 5 subjects
// in turn
NEXT Subject
IndividualAvg ← IndividualTotal / 5
OUTPUT “The average of student ”, Student, “is : ”, IndividualAvg
TotalAverage ← TotalAverage + IndividualAvg // Totaling of average being done for 50 students in
// turn
NEXT Student
OverallAverage ← TotalAverage / 50
OUTPUT “The overall average of all the students is ”, OverallAverage
Problem: A one-dimensional array, Names has students’ names stored for 50 students in it. Another one-
dimensional array, Marks has subject mark of one subject stored for the students. Find the highest and
lowest from the Marks array and display the name of the student who has achieved it. The names and marks
have been stored using the same index. Assume that there will be one highest and one lowest in the array.
Write down the pseudocode for the above scenario.
The index of any student’s data is same in both arrays. For example, a student named in index 4 of Names
Page 9 of 17
array corresponds to the data in index 4 of the Marks array.
You need to declare all the data structures before use.
//The array which will be used to do the totaling needs to be initialized 0 for each element before use
FOR Student ← 1 TO 20
TotalMarks [Student] ← 0
NEXT Student
Problem: A 2D array, SalesReport has sales reports stored for 50 sales persons of 12 months of a year. The
months are represented in consecutive columns. Calculate the total sales of each month and store it in a 1D
array, TotalSales. Display the total sales of each month.
Problem: A two-dimensional array Account[] contains account holders’ names and passwords for a banking
program.
Another two-dimensional array AccDetails[] has columns containing the following details:
• Column one stores the balance – the amount of money in the account, for example 2500.00
• Column two stores the withdrawal limit – the amount of money that can be withdrawn at one time,
for example 200.00
Page 10 of 17
The index of the two arrays represents the same account holder. For example, The information of
Account[20,1] and Account[20,2] and also AccDetails[20,1] and AccDetails[20,2] represents the same
account holder.
Explanation: Nested loop was not needed here as particular column was accessed.
Problem: A one-dimensional array Days[ ] contains the names of the days of the week like Sunday,
Monday etc. A two-dimensional array Readings[ ] contains 24 temperature readings, taken once an hour, for
each of the seven days of the week. The data in both the Days array and Readings array have already been
stored.
Another one-dimensional array AverageTemp[] will be used to store the average temperature for each day of
the week.
The position of any day’s data is the same in all three arrays. For example, if Wednesday is in index 4 of
Days[ ], Wednesday’s temperature readings are in index 4 of Readings[ ] and Wednesday’s average
temperature is in index 4 of AverageTemp[ ]
A program requires to
• Calculate and store the average temperature for each day of the week
• Find the lowest average temperature of the week and display the name of the day for which the
lowest average temperature was found out
• Assume that there will be only one lowest temperature of the week
Page 11 of 17
DECLARE Day, Hour, LowestIndex : INTEGER
DECLARE Total, Lowest : REAL
Lowest ← 100.0
N.B. To access all the elements of a 2D array you have to understand whether you have to access all
the columns for each row or all the rows for each column. If it is the case in which all the columns
need to be accessed for each row then the outer loop should be for rows and the inner loop should be
for the columns. If it is the case in which all the rows need to be accessed for each column then the
outer loop should be for columns and the inner loop should be for the rows. In both the cases the
array indices must be [Row, Column].
//Displaying the names of the students who achieved the highest mark
FOR Count ← 1 TO 35
IF Marks [Count]=Highest
THEN
OUTPUT “The highest mark achieved by:”, Names[Count]
ENDIF
NEXT Count
Problem: A 1D array, Marks has 30 student marks stored in it. Another 1D array, Names has names for
those 30 students stored in it. Find the highest and the second highest of those marks and display the name/s
of those students. There may be more than one student with highest and second highest marks.
Highest ← 0
SecondHighest ← -1
FOR Count ← 1 TO 30
IF Marks [Count]>Highest
THEN
SecondHighest ← Highest
Highest ← Marks [Count]
ELSE
IF Marks [Count] > SecondHighest AND Marks [Count] < > Highest
THEN
SecondHighest ← Marks [Count]
ENDIF
ENDIF
NEXT Count
//Displaying the names of the students who achieved the highest mark
FOR Count ← 1 TO 30
IF Marks [Count] = Highest
THEN
OUTPUT “Highest mark achieved by:”, Names[Count]
ENDIF
NEXT Count
Page 13 of 17
//Displaying the names of the students who achieved the second highest mark
FOR Count ← 1 TO 30
IF Marks [Count] = SecondHighest
THEN
OUTPUT “Second highest mark achieved by:”, Names[Count]
ENDIF
NEXT Count
LINEAR SEARCH ALGORITHM
Linear search or sequential search is a method for finding an element within a list. In Linear Search, each
element of the list is visited one by one in a sequential fashion to find the desired element. It sequentially
checks each element of the list until a match is found or the whole list has been searched. Linear search can
be performed on unsorted array as well as sorted array.
The algorithm for efficient linear search can be broken down into the following steps:
1 Start: Begin at the first element of the list
2 Compare: Compare the current element with the desired element
3 Found: If the current element is equal to the desired element, then end the searching
4 Move: Otherwise, move to the next element in the list
5 Repeat: Repeat steps 2-4 until we have reached the end of list
6 Not found: If the end of the list is reached without finding the desired element, that means the element is
not present in the list
Problem: A one-dimensional array, ItemNumber has 50 items already stored in it and each of the item is
stored as a whole number. Take an item number as an input from a user and check if the item is in the array.
If the item is found then display the index number with proper message and stop the algorithm. If the item is
not found in the array, then display a proper message for not found.
You need to declare all the data structures before use.
Index ← 1
IsFound ← FALSE // This is a Boolean variable and used as a FLAG. This variable has been initialized as
//FALSE and during the execution of the program this value will be changed to TRUE if the item is found
//and this will stop the execution of the loop
OUTPUT “Please enter the item number you are looking for: ”
INPUT SearchItem
WHILE IsFound = FALSE AND Index <= 50 DO //As long as both the conditions are TRUE, the loop
//will continue
IF ItemNumber[Index] = SearchItem
THEN
OUTPUT “The item found at location ”, Index
IsFound ← TRUE //This will stop the loop as the condition of WHILE loop will be FALSE next
Page 14 of 17
//time
ELSE
Index ← Index + 1 // Incrementing index so that search continues to check with the next index
//value
ENDIF
ENDWHILE
IF IsFound = FALSE //This can be written also as IF Index > 50 or IF Index = 51
THEN
OUTPUT “The item was not found”
ENDIF
IF Index > 50
THEN
OUTPUT “The item was not found”
ENDIF
Problem: A program will search for a name in a one-dimensional array, Names which already has 100
names stored in it. The program takes input of a name from a user and counts the number of times the name
was found in the array. Write down the pseudocode for the above scenario with proper input and output
message.
You need to declare all the data structures before use.
Page 15 of 17
NameCount ← 0
OUTPUT “Enter a name to search: ”
INPUT SearchName
FOR Index ← 1 TO 100
IF SearchName = Names[Index]
THEN
NameCount ← NameCount + 1
ENDIF
NEXT Index
OUTPUT “The name ”, SearchName, “was found ”, NameCount, “times”
Problem: A subroutine, FindElement receives a whole number as a parameter. It checks if the parameter
value is found in the second column of a global two-dimensional array, Number. The array is made up of 50
rows and 5 columns with all whole numbers. If the value is found then it returns TRUE and stops the
program otherwise it returns FALSE after the search is complete. Write down the pseudocode for the
subroutine.
You need to declare all the local data structures before use.
Index ← 1
Found ← FALSE
WHILE Index <=50 AND NOT Found DO //As long as both the conditions are TRUE, the loop
//will continue
IF Value = Number[Index, 2] //Accessing second column of each row
THEN
Found ← TRUE //This will stop the loop as the condition of WHILE loop will evaluate as
//FALSE next time
ELSE
Index ← Index + 1 // Incrementing index so that search continues to check with the next
//index value
ENDIF
ENDWHILE
RETURN Found
ENDFUNCTION
Problem: A 1D array, Number, has 10 numbers stored in it and the numbers are all in whole numbers and
are stored in ascending order. Write down the subroutine which receives the array and a value as two
parameters. It then searches the value in the array and if found then returns the index or returns -1 if not
found.
Call the subroutine and based on the return value display a proper message.
Write down the efficient linear search algorithm for the subroutine.
Page 17 of 17