Introduction to Arrays 1
Introduction to Arrays 1
ARRAYS
2
Introduction to Arrays
Overview
An array is a data structure used to store multiple values of the same data type in a single
variable. Arrays are particularly useful when managing a large dataset, such as storing the
marks of students in a class or tracking the temperature over 30 days.
Without arrays, you would need separate variables for each value, such as:
var
day1, day2, day3: Integer;
If there are 30 days, this becomes unmanageable. Arrays simplify this by using a single
variable to store all the values.
var
temperatures: array[1..30] of Integer;
Declaring Arrays
Syntax in pascal(delphi)
var
arrayName: array[lower..upper] of dataType;
var
studentMarks: array[1..5] of Integer;
Legendary 🔥
3
Each position in an array is identified by an index. The index range is specified during
the declaration.
Visualization
Index Element
1 87
2 92
3 76
4 88
5 90
(Akunankinga even if we place it horizontally or vertically as long you know to
differentiate le Index from le element)
studentMarks[1] := 87;
studentMarks[2] := 92;
Example Program
This program initializes an array and calculates the average of student marks:
program CalculateAverage;
var
studentMarks: array[1..5] of Integer;
i, total, average: Integer;
begin
total := 0;
Legendary 🔥
4
// Calculate total
for i := 1 to 5 do
total := total + studentMarks[i];
// Calculate average
average := total div 5;
An array doesn't have to start at index 1. You can define custom ranges:
Sibonelo :
var
temperatures: array[-5..5] of Real;
Character Indices
var
gradeCount: array['A'..'F'] of Integer;
Default Values
var
days: array[1..7] of String = ('Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
(Remember you cannot innitialise a local variable so if you want to have default values you
must declare you array as a global varable)
Legendary 🔥
5
program FillArray;
var
marks: array[1..3] of Integer;
iMark: Integer;
begin
for i := 1 to 3 do
begin
imark:= strtoint(InputBox(‘Student mark’,'Enter Mark,’’);
memo.lines.add(inttostr(marks[i]));
end;
end.
for i := 1 to 3 do
Memo.lines.add('Mark of student ', i, ': ', marks[i]);
Visual Representation
Example: Array with Custom Index (-5..5)
Index: -5 -4 -3 -2 -1 0 1 2 3 4 5
Value: 10 15 20 25 30 35 40 45 50 55 60
Index: A B C D E F
Value: 10 20 30 40 50 60
Legendary 🔥
6
Let’s work with a scenario where we record daily temperatures for a week.
Example Scenario
Imagine we want to analyze daily temperature readings for seven days. An array will
store these temperatures, and we will use aggregate algorithms to derive insights like
average temperature, the hottest day, and the coldest day.
Array Declaration
var
temperatures: array[1..7] of Real; // Stores temperatures for 7 days
Algorithm
Code
program AverageTemperature;
var
temperatures: array[1..7] of Real;
i: Integer;
sum, average: Real;
begin
// Example temperatures
temperatures[1] := 23.5;
temperatures[2] := 25.2;
Legendary 🔥
7
temperatures[3] := 22.8;
temperatures[4] := 24.1;
temperatures[5] := 26.0;
temperatures[6] := 21.4;
temperatures[7] := 23.9;
sum := 0.0;
// Calculate sum
for i := 1 to 7 do
sum := sum + temperatures[i];
// Calculate average
average := sum / 7;
Algorithm
Code
program MaxTemperature;
var
temperatures: array[1..7] of Real;
i: Integer;
maxTemp: Real;
begin
// Example temperatures
temperatures[1] := 23.5;
temperatures[2] := 25.2;
temperatures[3] := 22.8;
temperatures[4] := 24.1;
temperatures[5] := 26.0;
temperatures[6] := 21.4;
temperatures[7] := 23.9;
Legendary 🔥
8
Algorithm
Code
program MinTemperature;
var
temperatures: array[1..7] of Real;
i: Integer;
minTemp: Real;
begin
// Example temperatures
temperatures[1] := 23.5;
temperatures[2] := 25.2;
temperatures[3] := 22.8;
temperatures[4] := 24.1;
temperatures[5] := 26.0;
temperatures[6] := 21.4;
temperatures[7] := 23.9;
Diagrams
Array Visualization
Day 1 2 3 4 5 6 7
Legendary 🔥
9
Best Practices
Initialize Variables: Always initialize aggregate variables like sum, max, and min
before use.
Use Loops: Leverage loops to iterate through array elements efficiently.
Edge Cases: Consider empty arrays or arrays with a single element.
Legendary 🔥
10
Bubble Sort compares adjacent elements in an array and swaps them if necessary. It
continues this process over multiple passes until the array is sorted. After each pass:
Example Scenario
Let’s sort the scores of a class quiz: [45, 32, 67, 23, 89].
program BubbleSortExample;
Legendary 🔥
11
var
scores: array[1..5] of Integer = (45, 32, 67, 23, 89);
i, j, temp: Integer;
swapped: Boolean;
begin
Memo.lines.add('Original array: ');
for i := 1 to 5 do
Memo.lines.add(inttostr(scores[i], ' '));
// Bubble Sort
repeat
swapped := False;
for i := 1 to 4 do // Adjust range for last unsorted element
begin
if scores[i] > scores[i + 1] then
begin
// Swap elements
temp := scores[i];
scores[i] := scores[i + 1];
scores[i + 1] := temp;
swapped := True;
end;
end;
until not swapped;
Visualization
Pass 1
Index 0 1 2 3 4
Original 45 32 67 23 89
After Pass 32 45 23 67 89
Pass 2
Index 0 1 2 3 4
Original 32 45 23 67 89
After Pass 32 23 45 67 89
Legendary 🔥
12
Pass 3
Index 0 1 2 3 4
Original 32 23 45 67 89
After Pass 23 32 45 67 89
1. Descending Order: Change the condition from > to < in the comparison:
2. Optimized Bubble Sort: Track the last swapped position to avoid redundant
comparisons.
Summary
Bubble Sort is a simple yet powerful algorithm for educational purposes. It demonstrates
fundamental concepts like iteration, conditionals, and swapping in arrays. By modifying
its conditions and stopping criteria, the algorithm can handle various sorting needs.
Legendary 🔥
13
Scenario
Imagine sorting a list of prices for different items in a shopping cart: [99, 35, 120,
50, 75]. The goal is to arrange the prices in ascending order for better analysis.
Steps:
1. Start with the First Element: Assume the first element is the smallest.
2. Find the Smallest Element: Compare the assumed smallest element with the rest
of the array.
3. Swap: If a smaller element is found, swap it with the assumed smallest element.
4. Repeat: Move to the next position and repeat the process for the remaining
unsorted portion of the array.
5. Finish: Continue until the entire array is sorted.
Visualization
Unsorted Array:
Index 0 1 2 3 4
Value 99 35 120 50 75
Step-by-Step Sorting:
Pass 1: Find the smallest value [35] and swap it with the first element.
Index 0 1 2 3 4
Legendary 🔥
14
Value 35 99 120 50 75
Pass 2: Find the smallest value [50] in the remaining array and swap it with the second
element.
Index 0 1 2 3 4
Value 35 50 120 99 75
Pass 3: Find the smallest value [75] and swap it with the third element.
Index 0 1 2 3 4
Value 35 50 75 99 120
Pseudocode
for i = 0 to n-2 do
minIndex = i
for j = i+1 to n-1 do
if array[j] < array[minIndex] then
minIndex = j
if minIndex ≠ i then
swap(array[i], array[minIndex])
Code
program SelectionSortExample;
var
prices: array[1..5] of Integer = (99, 35, 120, 50, 75);
i, j, minIndex, temp: Integer;
begin
// Display the original array
Memo.lines.add('Original array: ');
for i := 1 to 5 do
Memo.lines.add(inttostr(prices[i], ' '));
// Selection Sort
Legendary 🔥
15
for i := 1 to 4 do
begin
minIndex := i;
for j := i + 1 to 5 do
begin
if prices[j] < prices[minIndex] then
minIndex := j;
end;
// Swap the smallest element with the current element
temp := prices[i];
prices[i] := prices[minIndex];
prices[minIndex] := temp;
end;
Modifications
1. Descending Order:
o Change the comparison from < to > in the if condition:
Legendary 🔥
16
Linear search is a simple and intuitive algorithm used to search for a specific element in
an array. It involves traversing the array sequentially from the first to the last element,
comparing each value with the target.
Scenario
Imagine a system for tracking student attendance where each student has an ID stored in
an array. A teacher wants to check if a specific student ID exists in the list and, if so,
determine its position. For example, the list of IDs is [1023, 1001, 1045, 1010,
1032], and the teacher searches for the ID 1010.
1. Start at the Beginning: The algorithm begins by examining the first element in the
array.
2. Compare: Each element is compared with the target value.
3. Record Position (if found): If the element matches the target, its position is
recorded.
4. Continue Searching (if necessary): The algorithm continues checking for
additional matches or stops if searching for a single occurrence.
5. Result: If no match is found after traversing the array, a message indicates the value
does not exist.
Visualization
Iterations:
Legendary 🔥
17
Pseudocode
found ← false
index ← 0
if found then
print "Value found at position ", position
else
print "Value not found in the array"
Code
program LinearSearchExample;
var
studentIDs: array[1..5] of Integer = (1023, 1001, 1045, 1010, 1032);
target, position, i: Integer;
found: Boolean;
begin
// Initialize variables
found := False;
position := -1;
// Linear Search
for i := 1 to 5 do
begin
if studentIDs[i] = target then
begin
found := True;
position := i;
Break; // Exit loop after finding the value
end;
end;
// Display results
if found then
Legendary 🔥
18
Diagram
Below is a step-by-step diagram for the search of 1010 in [1023, 1001, 1045, 1010,
1032].
Before Search:
Index 0 1 2 3 4
Value 1023 1001 1045 1010 1032
During Search:
Key Concepts
1. Efficiency: Linear search has a time complexity of O(n)O(n)O(n), where nnn is the
number of elements in the array.
2. Versatility: It works for both sorted and unsorted arrays.
3. Ease of Implementation: Linear search is straightforward to code and does not
require additional memory.
1. Find All Occurrences: Modify the loop to record all positions where the target
value is found.
2. Partial Matches: Use a condition to check substrings (e.g., for arrays of strings).
3. Case Sensitivity: Convert all values to lowercase or uppercase when searching
strings.
4. Performance: For sorted arrays, use a more efficient algorithm like Binary Search
instead.
Legendary 🔥
19
Scenario
A library system stores book IDs in a sorted array. A librarian wants to check if a
particular book ID exists in the inventory. For example, the array contains the IDs [101,
203, 305, 407, 509, 611], and the librarian searches for the book ID 305.
1. Initial Setup:
o Start with two pointers: lower (beginning of the array) and upper (end of
the array).
o Calculate the midpoint as the average of lower and upper.
2. Comparison:
o If the value at midpoint equals the target, the search is successful.
o If the value is less than the target, narrow the search to the right half.
o If the value is greater, narrow the search to the left half.
3. Repeat:
o Recalculate the midpoint and repeat the comparison until the target is found
or the search range becomes empty (lower > upper).
Visualization
Pseudocode
Legendary 🔥
20
if found:
return position
else:
return -1
Implementation
program BinarySearchExample;
var
bookIDs: array[1..6] of Integer = (101, 203, 305, 407, 509, 611);
target, lower, upper, mid, position: Integer;
found: Boolean;
begin
// Initialize variables
found := False;
lower := 1; // First index of the array
upper := 6; // Last index of the array
position := -1;
// Binary Search
while (lower <= upper) and (not found) do
begin
mid := (lower + upper) div 2; // Calculate midpoint
if bookIDs[mid] = target then
begin
found := True;
position := mid;
end
else if bookIDs[mid] < target then
lower := mid + 1
else
upper := mid - 1;
Legendary 🔥
21
end;
// Display results
if found then
Memo.lines.add('Book ID ', target, ' found at position ', position)
else
Memo.lines.add('Book ID ', target, ' not found in the array');
end.
Diagram
Below is a step-by-step diagram of Binary Search for the target value 305 in the array
[101, 203, 305, 407, 509, 611].
1. Initial State
Key Features
1. Efficiency:
o Time Complexity: O(logn)O(\log n)O(logn)
o Reduces search space by half in each iteration.
2. Limitations:
o Works only on sorted arrays.
o Requires pre-sorting if the array is unsorted.
Enhancements
Legendary 🔥
22
Arrays are a data structure used to store multiple values. While iterating through an array
is common, specific indices allow us to directly access and manipulate a particular
element without looping through the entire array. This capability is especially useful
when the index represents a meaningful value, such as the result of an operation or a
category.
Scenario
Imagine a voting system where people cast votes for candidates numbered 1 to 5. Each
vote corresponds to a candidate's index in an array. Using specific indices, we can
efficiently record and update the vote count for each candidate.
1. Direct Access: Accessing an array at a specific index is faster than iterating through
the array.
2. Simpler Logic: Eliminates the need for conditional statements to identify which
element to update.
3. Efficiency: Ideal for situations where each index has a specific meaning, such as
counting occurrences or mapping categories.
Explanation
In a voting system, an array votes is used to store the number of votes for candidates 1 to
5. When a vote is cast, the corresponding candidate’s position in the array is incremented.
Diagram
Index: 1 2 3 4 5
Votes: 0 0 0 0 0
Index: 1 2 3 4 5
Votes: 2 2 1 0 0
Legendary 🔥
23
Implementation
program VotingSystem;
var
votes: array[1..5] of Integer; // Array to store vote counts
candidate, i, totalVotes: Integer;
begin
// Initialize the votes array
for i := 1 to 5 do
votes[i] := 0;
// Simulate voting
Totalvotes:=strtoint(inputbox(‘number of Votes,’'Enter the number of
votes: ‘,’');
for i := 1 to totalVotes do
begin
candidate:=strtoint(inputbox('Vote’,’Cast your vote (1 to 5):
',’’));
Specific indices can also be used to group values into ranges. For example:
1 to 25 is stored in group[1].
26 to 50 is stored in group[2].
51 to 75 is stored in group[3].
Code:
Legendary 🔥
24
program AgeCategorization;
var
ageGroups: array[1..4] of Integer; // Groups: 1-25, 26-50, 51-75, 76+
age, i: Integer;
begin
// Initialize age groups
for i := 1 to 4 do
ageGroups[i] := 0;
Diagram
Legendary 🔥
25
Ages: 15, 34, 72, 18, 49, 55, 77, 19, 66, 80
Another classic example of specific indices is rolling a dice and recording the frequency
of each outcome.
Code:
program DiceThrowing;
var
diceResults: array[1..6] of Integer;
i, roll: Integer;
begin
// Initialize dice results
for i := 1 to 6 do
diceResults[i] := 0;
// Display results
Memo.lines.add('Dice results after 50 rolls:');
for i := 1 to 6 do
Memo.lines.add(inttostr(i)+ ': '+ inttostr(diceResults[i])+’
times');
end.
Best Practices
Legendary 🔥
26
Parallel Arrays
Introduction
Parallel arrays are two or more arrays whose elements share a relationship by their
indices. The value at a given position in one array corresponds to a related value at the
same position in another array. These arrays must have the same size, but their data types
can differ.
Imagine you are managing an inventory system for a store. Two arrays are used:
The relationship between these arrays ensures that the stock quantity at position i in
itemQuantities corresponds to the item name at position i in itemNames.
Diagram
Initial State
Index 1 2 3 4
ItemNames Pen Notebook Erasor Pencil
ItemQuantities 50 30 20 15
This relationship ensures that the value at position 1 in itemNames ("Pen") corresponds to
50 in itemQuantities.
Legendary 🔥
27
Core Concepts
1. Maintaining Relationships
Operations on one array, such as adding or removing elements, must be mirrored in the
other array to maintain their parallel relationship.
Parallel arrays make it easy to perform operations like finding the quantity of a specific
item or locating an item with the highest/lowest quantity.
Implementation
program InventoryManagement;
const
MAX_ITEMS = 100;
var
itemNames: array[1..MAX_ITEMS] of String;
itemQuantities: array[1..MAX_ITEMS] of Integer;
itemCount, i, maxIndex, minIndex: Integer;
newItem: String;
newQuantity: Integer;
begin
// Initialize arrays
itemCount := 4;
itemNames[1] := 'Pen'; itemQuantities[1] := 50;
itemNames[2] := 'Notebook'; itemQuantities[2] := 30;
itemNames[3] := 'Eraser'; itemQuantities[3] := 20;
itemNames[4] := 'Pencil'; itemQuantities[4] := 15;
// Display inventory
Memo.lines.add('Initial Inventory:');
for i := 1 to itemCount do
Memo.lines.add(inttostr(itemNames[i]), ': ', inttostr
(itemQuantities[i]));
Legendary 🔥
28
for i := 2 to itemCount do
begin
if itemQuantities[i] > itemQuantities[maxIndex] then
maxIndex := i;
if itemQuantities[i] < itemQuantities[minIndex] then
minIndex := i;
end;
// Display results
Memo.lines.add('Updated Inventory:');
for i := 1 to itemCount do
Memo.lines.add(itemNames[i], ': ', itemQuantities[i]);
To sort parallel arrays, the sorting logic must operate on all related arrays to maintain
their relationship.
Code:
program SortInventory;
const
MAX_ITEMS = 100;
var
itemNames: array[1..MAX_ITEMS] of String;
itemQuantities: array[1..MAX_ITEMS] of Integer;
itemCount, i, j, tempQuantity: Integer;
tempName: String;
begin
// Initialize arrays
itemCount := 4;
itemNames[1] := 'Pen'; itemQuantities[1] := 50;
itemNames[2] := 'Notebook'; itemQuantities[2] := 30;
itemNames[3] := 'Eraser'; itemQuantities[3] := 20;
itemNames[4] := 'Pencil'; itemQuantities[4] := 15;
Legendary 🔥
29
Diagram of Sorting
Before Sorting
Index 1 2 3 4
ItemNames Pen Notebook Erasor Pencil
ItemQuantities 50 30 20 15
Index 1 2 3 4
ItemNames Pencil Erasor Notebook Pen
ItemQuantities 15 20 30 50
Key Takeaways
1. Consistency: Always perform the same operations on all parallel arrays to maintain
their relationship.
2. Initialization: Ensure all arrays are initialized with proper values.
3. Sorting: When sorting parallel arrays, synchronize the logic to keep corresponding
data aligned.
Legendary 🔥
30
Use Cases
Parallel arrays offer a powerful way to manage and process related data efficiently. By
adhering to the principles outlined here, you can ensure the integrity and consistency of
your data.
Introduction
In this section, we focus on how to load data from a text file into an array. This is useful
when handling large sets of data that are stored externally. For example, imagine we have
a file that contains a list of product names and their prices. We want to load this data into
two separate arrays: one for the product names and one for the prices.
Consider an inventory system where we have a text file named products.txt that
contains product names and their prices. Each line in the file looks like this:
Apple, 1.25
Banana, 0.75
Orange, 1.50
The goal is to load each product's name into productNames and its corresponding price
into productPrices.
Diagram
Legendary 🔥
31
Apple, 1.25
Banana, 0.75
Orange, 1.50
Index 1 2 3
productNames Apple Banana Orange
productPrices 1.25 0.75 1.50
Core Concepts
1. Array Initialization: We initialize arrays to store the data. The arrays should be
large enough to hold all the values from the file.
2. File Handling: Using file handling functions to read data from the text file line by
line.
3. Data Extraction: Extracting product names and prices from each line, then storing
them into the corresponding arrays.
4. Parallel Arrays: When dealing with parallel arrays, ensure that the corresponding
data is stored in the same index across all arrays.
Step 1: Setup
Create two arrays: productNames (of type String) and productPrices (of type
Real).
Use a size variable to track how many items have been loaded into the arrays.
Implementation
program LoadProductData;
uses
SysUtils;
const
MAX_PRODUCTS = 100;
var
productNames: array[1..MAX_PRODUCTS] of String;
productPrices: array[1..MAX_PRODUCTS] of Real;
size, i: Integer;
productFile: TextFile;
line, productName: String;
Legendary 🔥
32
productPrice: Real;
commaPos: Integer;
begin
// Initialize size to 0
size := 0;
// Find the position of the comma (to separate name and price)
commaPos := Pos(',', line);
1. File Handling:
o The AssignFile function associates the productFile variable with the
products.txt file.
o Reset(productFile) opens the file for reading.
o The program then reads each line of the file using ReadLn and processes the
data.
Legendary 🔥
33
2. Data Extraction:
o For each line, the Pos(',', line) function finds the position of the
comma.
o Copy(line, 1, commaPos - 1) extracts the product name before the
comma.
o Copy(line, commaPos + 1, Length(line) - commaPos) extracts the
product price after the comma and converts it to a real number using
StrToFloat.
3. Loading into Arrays:
o The size variable tracks how many products have been processed.
o The productNames array holds the product names, and productPrices
holds the prices.
4. Displaying Data:
o The program loops through the arrays and prints out the loaded product
names and prices.
In cases where the data file contains both a name and a corresponding value (like the
product name and price), the values are stored in parallel arrays. Both arrays should be
updated simultaneously to maintain the relationship.
Index 1 2 3
productNames Apple Banana Orange
productPrices 1.25 0.75 1.50
Conclusion
Loading data from a text file into an array is a straightforward process. By following the
steps outlined in the program, you can efficiently read and store data from external files
into arrays for further processing. This technique is useful in various scenarios, such as
managing product inventories, storing user data, or importing datasets for analysis.
Legendary 🔥
34
Key Points:
Legendary 🔥
35
Legendary 🔥