0% found this document useful (0 votes)
9 views

Arraysand Linear Search

Uploaded by

Tleance
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Arraysand Linear Search

Uploaded by

Tleance
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Computer Science

Teacher: Maruf Ahmed


Arrays
Arrays:
By definition, an array is a list of variables with the same data type and a name (identifier). For example,
you could have an array of integers or an array of string or an array of anything that has a defined data
type. When we work with a single item, we only need to use one variable. However, if we have a list of
items which are of similar type to deal with, we need to declare an array of variables instead of using a
variable for each item.
For example, if we need to enter one hundred names, it is difficult to declare 100 different variables; this
is a waste of time and effort. So, instead of declaring one hundred different variables, we need to declare
only one array. We differentiate each item in the array by using subscript, the index value of each item,
for example name[1], name[2], name[3] etc., which will make declaring variables streamline and much
more systematic.

Why do we use arrays?


 easy to handle / modify
 reduces the number of variables
 arrays have an index which identifies each element uniquely
 programs are easier to debug
 less lines of codes required

The important characteristics of an array are:


 Each element has the same data type
 A common identifier is used for an array with an index for each element to identify each
element uniquely
 The entire array is stored contiguously in memory (that is, there are no gaps between elements).

Arrays can be one-dimensional (1D) or two-dimensional (2D).

Dimension: The dimension is the number of indices required to access an element


Index: The index is the position of the element in an array

Example of dimension and index in an array:


For example, A[15] is the 15th element of a one-dimensional array.
For example, B[10][5] is the element in the 10th row and 5th column of a two-dimensional array.

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.

Pseudocode to declare 1D array:


 DECLARE <Identifier name> : ARRAY[Lowerbound : Upperbound] OF data type

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.

For example, DECLARE Weight : ARRAY[1:5] OF REAL

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.

Weight 50.25 85.0 35.75 22.0 39.0


Index 1 2 3 4 5

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

DECLARE Weight : ARRAY[0:4] OF REAL

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

Pseudocode to declare a 2D array:


 DECLARE <Identifier name> : ARRAY[Lowerbound : Upperbound, Lowerbound :
Upperbound] OF data type
 The first Lowerbound : Upperbound indicates the start index and last index of the row and the
second Lowerbound : Upperbound indicates the start index and last index of the column. In each
case the lowerbound and the upperboud will be separated by colon ( : ).
 Both the indices for row and column will be given within one square bracket [ ] and the row part
and column part will be separated by a comma ( , ).

For example, DECLARE Grade : ARRAY[1:5, 1:3] OF CHAR

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.

For example, Grade[3, 2] has the value F

The previous declaration could have been made in the following way also

DECLARE Grade : ARRAY[0:4, 0:2] OF CHAR


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
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.

DECLARE Num : ARRAY[1:50] OF INTEGER


DECLARE Index : INTEGER

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.

DECLARE Number : ARRAY[0:19, 0:4] OF REAL


DECLARE Row, Column : INTEGER

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

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.

Storing / populating values into two different one-dimensional arrays:


Problem: Write down the pseudocode to take input of names and weights of 30 students in two different
one-dimensional arrays. The data must be stored using the same index of the two arrays. You need to
declare all the data structures before use.

DECLARE StudentName : ARRAY[1:30] OF STRING


DECLARE StudentWeight : ARRAY[1:30] OF REAL
DECLARE SName : STRING
DECLARE SWeight : REAL
DECLARE Index : INTEGER

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.

Displaying values from multiple one-dimensional array 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]
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.

Storing / populating values in a two-dimensional array:


Problem: A class has 30 students. Each student takes 5 subjects. Take input of the students‟ marks which
are all whole numbers and store them in a 2D array. You need to declare all the data structures before
use.

DECLARE StudentMark : ARRAY [1:30, 1:5] OF INTEGER


DELARE Student, Subject : INTEGER

FOR Student ← 1 TO 30 //Outer loop for row


OUTPUT “Input of marks for student ”, Student, “: ”
FOR Subject ← 1 TO 5 //Inner loop for column
OUTPUT “Enter marks for subject ”, Subject, “: ”
INPUT StudentMark[Student, Subject]
NEXT Subject
NEXT Student

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.

Displaying values from a two-dimensional array:


Here is how to display (output) all the values from a 2D array named StudentMark which were stored in
the previous section.

FOR Student ← 1 TO 30 //Outer loop for row


OUTPUT “Student ”, Student, “ has obtained the following marks”
FOR Subject ← 1 TO 5 //Inner loop for column
OUTPUT “Marks of subject”, Subject, “: ”, StudentMark[Student, Subject]
NEXT Subject
NEXT Student

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

FOR Index ← 1 TO 100


OUTPUT “Enter name of student: ”, Index, “: ”
INPUT StudentNames[Index]
OUTPUT “Enter mark of student: ”, 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
NEXT Index

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.

DECLARE MonthTotal, DayTotal : REAL


DECLARE Day, Hour : INTEGER

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.

Highest ← Marks[1] //Value of first element has been assigned to Highest


Lowest ← Marks[1] //Value of first element has been assigned to Lowest
FOR Student ← 2 TO 50 //Loop starts from second element as first element value has been assigned to
//both Highest and Lowest
IF Marks[Student] > Highest
THEN
Highest ← Marks[Student]
HighestIndex ← Student //Storing the index for highest for getting the name of that index
ENDIF
IF Marks[Student] < Lowest
THEN
Lowest ← Marks[Student]
LowestIndex ← Student //Storing the index for lowest for getting the name of that index
ENDIF
NEXT Student
OUTPUT “Student name: ”, Names[HighestIndex], “got the highest: ”, Marks[HighestIndex]
OUTPUT “Student name: ”, Names[LowestIndex], “got the lowest: ”, Marks[LowestIndex]

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.

DECLARE Total : ARRAY[1:5] OF INETEGER


DECLARE Student, Subject : INTEGER

//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

//Displaying names and totals


FOR Student ← 1 TO 50
OUTPUT “Student name: ”, Names[Student], “got the total: ”, Total[Student]
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.

There are 100 account holders in the bank.

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.

Highest ← AccDetails[1, 1] //First element value has been assigned to Highest


TotalBalance ← AccDetails[1, 1] //First element value has been assigned to TotalBalance

FOR Index ← 2 TO 100


TotalBalance ← TotalBalance + AccDetails[Index, 1] //First column of each row of a 2D array has
//been accessed
IF AccDetails[Index, 1] > Highest
THEN
Highest ← AccDetails[Index, 1]
NameIndex ← Index
ENDIF
NEXT Index
OUTPUT “Total balance is: ”, TotalBalance
OUTPUT “The highest balance is: ”, Highest, “ and name of the account holder is: ”, _
Account[NameIndex,1] // One element of a particular row and first column has been accessed

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.

DECLARE AverageTemp : ARRAY[1:7] OF REAL


DECLARE Day, Hour, LowestIndex : INTEGER
DECLARE Total, Lowest : REAL

//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

//Finding the lowest average temperature of the week


Lowest ← 100.0
FOR Day ← 1 TO 7

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]

Problem: Write an algorithm in pseudocode to


 input the names and marks of 35 students
 The algorithm stores the names and marks in two different one-dimensional arrays Name[ ] and
Mark[ ]
 Each mark is between 0 and 100 inclusive
 The highest mark awarded is found and the number of students with that mark is counted
 Display both of these values as output

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.

Solution using WHILE loop


DECLARE Index, SearchItem : INTEGER
DECLARE IsFound : BOOLEAN

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

What is a FLAG variable?


A flag variable, in its simplest form, is a variable you define to have one value until some condition is
true, in which case you change the variable's value.
Flag variable is used as a signal in programming to let the program know that a certain condition has met.
It usually acts as a Boolean variable indicating a condition to be either true or false.

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.

DECLARE NameCount, Index : INTEGER


DECLARE SearchName : STRING

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.

//Solution using WHILE loop


FUNCTION FindElement (Value : INTEGER) RETURNS BOOLEAN
DECLARE Index : INTEGER
DECLARE Found : BOOLEAN

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

//Solution using REPEAT loop


FUNCTION FindElement (Value : INTEGER) RETURNS BOOLEAN
DECLARE Index : INTEGER
DECLARE Found : BOOLEAN
Index ← 1
Found ← FALSE
REPEAT
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
UNTIL Index > 50 OR Found
RETURN Found
ENDFUNCTION

Page 15 of 15

You might also like