Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views17 pages

Arrays and Linear Search

The document provides an overview of arrays in computer science, explaining their definition, usage, and characteristics. It details one-dimensional and two-dimensional arrays, including how to declare, initialize, and manipulate them using pseudocode. Additionally, it covers examples of inputting and displaying data in arrays, emphasizing the importance of using loops for efficient data handling.
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)
10 views17 pages

Arrays and Linear Search

The document provides an overview of arrays in computer science, explaining their definition, usage, and characteristics. It details one-dimensional and two-dimensional arrays, including how to declare, initialize, and manipulate them using pseudocode. Additionally, it covers examples of inputting and displaying data in arrays, emphasizing the importance of using loops for efficient data handling.
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/ 17

Computer Science

Teacher: Maruf Ahmed


Arrays (One-dimensional and two-dimensional)
Arrays:
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 / features of an array are:


• Each element of an array 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 in contiguous memory location (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 referring to the 15th element of a one-dimensional array.
For example, B[10, 5] is referring to the element which is in the 10th row and 5th column of a two-
dimensional array.

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.

Pseudocode to declare 1D array:


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

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.

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

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.

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.

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

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 the last index of the row and the
second Lowerbound : Upperbound indicates the start index and the last index of the column. In
each case the Lowerbound and the Lowerbound 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 ( , ).
• No matter how many rows and columns a two-dimensional array has, the entire array must be of
the same data type

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

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

DECLARE Days : ARRAY[1:7] OF STRING


Days[1] ← “Sunday”
Days[2] ← “Monday”
Days[3] ← “Tuesday”
Days[4] ← “Wednesday”
Days[5] ← “Thursday”
Days[6] ← “Friday”
Days[7] ← “Saturday”

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.

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

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


DECLARE Row, Column : INTEGER

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.

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 (corresponding) 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 Count : 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.

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.

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 of the 5
subjects 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 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.

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


Page 6 of 17
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.

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

DECLARE MonthTotal, DayTotal, MonthTotalAverage, AverageEachDay, MonthAverage : REAL


DECLARE Day, Hour : INTEGER

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.

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 position as first position value has been assigned to
//both Highest and Lowest
IF Marks[Student] > Highest //Checking for highest
THEN
Highest ← Marks[Student]
HighestIndex ← Student //Storing the index for highest for getting the name of that index
ENDIF
IF Marks[Student] < Lowest //Checking for 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, TotalMarks. TotalMarks array needs to be
initialized before use. Display the name along with the total marks 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
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.

DECLARE TotalMarks : ARRAY[1:20] 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
TotalMarks [Student] ← 0
NEXT Student

FOR Student ← 1 TO 20 //Outer loop for Row


FOR Subject ← 1 TO 5 //Inner loop for Column
TotalMarks [Student] ← TotalMarks [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 TotalMarks
NEXT Subject
NEXT Student

//Displaying names and totals


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

DECLARE TotalSales : ARRAY[1:12] OF INTEGER


DECLARE i, j : INTEGER

//Column needs to be accessed first as column wise total is needed


FOR i ←1 TO 12 //Outer loop for accessing column
Total ← 0 //Resetting Total for each month
FOR j ← 1 TO 50 //Inner loop for accessing row
Total ← Total + SalesReport[j, i] //Array indices of 2D array is made up of row, column
NEXT j
TotalSales[i] ← Total
OUTPUT “Total sales for month ”, i, “is: ”, TotalSales[i]
NEXT i

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.

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 individual 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 //Storing the index to use it later
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

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

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

Page 11 of 17
DECLARE Day, Hour, LowestIndex : INTEGER
DECLARE Total, Lowest : REAL

Lowest ← 100.0

FOR Day ←1 TO 7 //Outer loop for Row


Total ← 0.0 //This needs to be reset 0.0 for totaling every day
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 used as index for AverageTemp as
// there are 7 days in the week

//Finding the lowest average temperature of the week


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]

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

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 Names[ ] and
Marks[ ]
• Each mark is between 0 and 100 inclusive. Assume that the input for marks is given as valid marks
• The highest mark awarded is found and the number of students with that mark is counted
• Display both of these values as output
• Display the name/s of the students who achieved the highest mark

HighestMark ← 0 //Initialized highest mark as 0


HighestMarkCounter ← 0 //Used as a counter
FOR Count ← 1 TO 35
OUTPUT "Please enter student name"
INPUT Names[Count]
OUTPUT "Please enter student mark"
INPUT Marks [Count]
Page 12 of 17
IF Marks [Count] = HighestMark //Checking if the value is equal to the current highest value
THEN
HighestMarkCounter ← HighestMarkCounter + 1
ELSE
IF Marks [Count] > HighestMark //Checking for the new highest
THEN
HighestMark ← Marks [Count] //Updating the new highest
HighestMarkCounter ← 1 //Resetting counter to 1 because this is now the new highest
ENDIF
ENDIF
NEXT Count
OUTPUT "There are ", HighestMarkCounter," students with the highest mark of ", HighestMark

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

What are the two reasons for a linear search to end?


- The value is found in an array index so no need to continue the search
- The end of the array is reached and the value is not found. So, the search needs to end

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.

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

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 REPEAT loop will be TRUE
//next time
ELSE
Index ← Index + 1 // Incrementing index so that search continues to check with the next index
//value
ENDIF
UNTIL IsFound OR Index > 50 //As long as both the conditions are FALSE the loop will continue

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

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.

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

//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 REPEAT loop will evaluate as
Page 16 of 17
//TRUE next time
ELSE
Index ← Index + 1 // Incrementing index so that search continues to check with the next
//index value
ENDIF
UNTIL Index > 50 OR Found //As long as both the conditions are FALSE the loop will continue
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.

FUNCTION SearchValue (Number: ARRAY, Value : INTEGER) RETURNS INTEGER


DECLARE i, ReturnValue : INTEGER
DECLARE Greater : BOOLEAN
i←1
Greater ← FALSE
ReturnValue ← -1
WHILE ReturnValue = -1 AND NOT Greater AND i < 11 DO
IF Number [i] = Value
THEN
ReturnValue ← i
ELSE
IF Number [i]> Value (or IF Value < y[i])
THEN
Greater ← TRUE
ELSE
i ←i+1
ENDIF
ENDIF
ENDWHILE
RETURN ReturnValue
ENDFUNCTION

// Calling the subroutine


Result ← SearchValue (Number, 11) //The array name must be Number here as first parameter and second
//parameter value can be any value
IF Result = -1
THEN
OUTPUT “The value is not present”
ELSE
OUTPUT “The value is present at position”, Result
ENDIF

Page 17 of 17

You might also like