Arraysand Linear Search
Arraysand Linear Search
One index is required for accessing an element of a 1D array, and 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.
Page 1 of 15
N.B. For a two-dimensional array, usually the number of rows is more than the number of columns.
However, it may not always be the case. But, remember that for accessing an element of a 2D array, the
row index has to be given first and then the column index separated by comma ( , ). That means the
format to access a 2D array is 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
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 to declare an array. 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 pseudoccode 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.
Page 2 of 15
Some example statements that can be performed in a one-dimensional array, Weight:
- OUTPUT Weight[3] //This will display 35.75 on the screen
- Weight[2] ← Weight[2] + 10.0 //Weight[2] had a value 85.0. This will be added with 10 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 in index 1 and 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 CHAR
data type 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 row index and column index both can start from 0 or from 1.
The previous declaration could have been made in the following way also
One thing to remember, the start index for the rows and columns cannot be a mixed up of 0 and 1. It has
Page 3 of 15
to be either 0 for both rows and columns or 1 for both rows and columns.
Initializing value 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 1 as its first value for the control variable Index. It will go inside the
loop in which one statement 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 in turn.
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 value in a two-dimensional array: Write down the pseudocode that will initialize each
element of a 2D array to 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.
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 row, the entire cycle of
Page 4 of 15
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.
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 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.
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]
Page 5 of 15
NEXT X
Explanation: Using one loop, we can access multiple different arrays if the values in different arrays are
stored using the same index.
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 now 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.
Page 6 of 15
//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 100 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:100] OF STRING
DECLARE StudentMarks : ARRAY[1:100] OF INTEGER
DECLARE Mark, Index : INTEGER
Solution 2:
DECLARE StudentNames : ARRAY[1:100] OF STRING
DECLARE StudentMarks : ARRAY[1:100] OF INTEGER
DECLARE Index : INTEGER
Page 7 of 15
FOR Index ← 1 TO 100
OUTPUT “Enter name of student: ”, Index, “: ”
INPUT StudentNames[Index]
REPEAT //This loop is being used for validation
OUTPUT “Enter mark of student: ”, Index, “: ”
INPUT StudentMarks[Index] //The array index being directly used
IF StudentMarks[Index] < 0 OR StudentMarks[Index] > 100
THEN
OUTPUT “Invalid mark. Re-enter”
INPUT StudentMarks[Index]
ENDIF
UNTIL StudentMarks[Index]>=0 AND StudentMarks[Index]<=100
NEXT Index
Problem: Temperature of a month (30 days) has already been stored in a 2D array. For each day the
temperature was taken for every hour (24 hours). Find the total temperature for each day and also the
total temperature for 30 days. Display the results. 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.
MonthTotal ← 0.0
FOR Day ← 1 TO 30 //Outer loop for Row
DayTotal ← 0.0
FOR Hour ← 1 TO 24 //Inner loop for Column
DayTotal ← DayTotal + Temperature[Day, Hour] //Totaling being done for 24 hours in turn
NEXT Hour
OUTPUT “The day total for day ”, Day, “is ”, DayTotal
MonthTotal ← MonthTotal + DayTotal //Totaling being done for 30 days in turn
NEXT Day
OUTPUT “The total temperature for all 30 days is ”, MonthTotal
Problem: A two-dimensional array, Marks already has subject marks stored for 50 students. Each student
takes 5 subjects. Find the average of each student separately and then find the average of all the students
together. Display the average values. Write down the pseudocode for the above scenario.
TotalAverage ← 0.0
FOR Student ← 1 TO 50 //Outer loop for Row
IndividualTotal ← 0
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
Page 8 of 15
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. Write down the pseudocode for the above scenario.
Problem: A one-dimensional array, Names has students names stored for 20 students in it. A 2D array,
Marks has subject marks stored for the students. Each student takes 5 subjects. Find the total of each
student separately and store it in another one-dimensional array, Total.
Display the name along with the total for each student.
The index of any student‟s data is same in both arrays. For example, a student named in index 4 of
Names 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
Total[Student] ← 0
NEXT Student
Page 9 of 15
FOR Student ← 1 TO 20 //Outer loop for Row
FOR Subject ← 1 TO 5 //Inner loop for Column
Total[Student] ← Total[Student] + Marks[Student, Subject] //Totaling being done for each element
of the 2D array and the value is stored in a 1D array. Row
counter has been used as index for Total
NEXT Subject
NEXT Student
Problem: A two-dimensional (2D) array Account[] contains account holders‟ names and passwords for a
banking program.
A 2D array AccDetails[] has two 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
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.
A program will find the total balance of all the accounts and also the name of the account holder who has
the highest balance. Display the results. Write down the pseudocode for the above problem.
Problem: A one-dimensional (1D) array Days[ ] contains the names of the days of the week like Sunday,
Page 10 of 15
Monday etc. A two-dimensional (2D) 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
been 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
Write down the pseudocode for the above scenario.
You need to declare all the data structures before use.
//Solution 1
Total ← 0.0
FOR Day ←1 TO 7 //Outer loop for Column
FOR Hour ← 1 TO 24 //Inner loop for Row
Total ← Total + Readings[Hour, Day] // Here row is 24 and column is 7. Row followed by
// column will be used for indices
NEXT Hour
AverageTemp[Day] ← Total / 24 // Day counter variable has been taken as index for AverageTemp as
// there are 7 days in the week
NEXT Day
//Solution 2
Total ← 0.0
FOR Day ←1 TO 7 //Outer loop for Row
FOR Hour ← 1 TO 24 //Inner loop for Column
Total ← Total + Readings[Day, Hour] // Here row is 7 and column is 24. Row followed by
// column will be used for indices
NEXT Hour
AverageTemp[Day] ← Total / 24 // Day counter variable has been taken as index for AverageTemp as
// there are 7 days in the week
NEXT Day
Page 11 of 15
IF AverageTemp[Day] < Lowest
THEN
Lowest ← AverageTemp[Day]
LowestIndex ← Day //Storing the index for the lowest for getting the day from Days[ ] array
ENDIF
NEXT Day
OUTPUT “The lowest temperature is ”, Lowest, “on day”, Days[LowestIndex]
HighestMark ← 0
HighestMarkStudents ← 0 //Used as a counter
FOR Count ← 1 TO 35
OUTPUT "Please enter student name"
INPUT Name[Count]
OUTPUT "Please enter student mark"
INPUT Mark[Count]
IF Mark[Count] = HighestMark //Checking if the value is equal to the current highest value
THEN
HighestMarkStudents ← HighestMarkStudents + 1
ENDIF
IF Mark[Count] > HighestMark //Checking for the new highest
THEN
HighestMark ← Mark[Count] //Updating the new highest
HighestMarkStudents ← 1 //Resetting counter to 1 because it is now the new highest
ENDIF
NEXT Count
OUTPUT "There are ", HighestMarkStudents," with the highest mark of ", HighestMark
Page 12 of 15
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.
The algorithm for 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, return true or index to the current
element and 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, return that the desired
element is not in the array
Problem: A one-dimensional array, ItemNumber has 50 items already stored in it. 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 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 as TRUE if
// the item is found which will be used to 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
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
//time
ELSE
Index ← Index + 1 // Incrementing counter so that search continues
ENDIF
ENDWHILE
IF NOT IsFound
THEN
OUTPUT “The item was not found”
Page 13 of 15
ENDIF
Solution using REPEAT loop
Index ← 1
IsFound ← FALSE
OUTPUT “Please enter the item number you are looking for: ”
INPUT SearchItem
REPEAT
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
//time
ELSE
Index ← Index + 1 // Incrementing counter so that search continues
ENDIF
UNTIL IsFound OR Index > 50
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.
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”
Page 14 of 15
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 otherwise it
returns FALSE. 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
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 be FALSE
//next time
ELSE
Index ← Index + 1 //Incrementing counter so that search continues
ENDIF
ENDWHILE
RETURN Found
ENDFUNCTION
Page 15 of 15