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

Introduction to Arrays 1

The document provides a comprehensive introduction to arrays, including their declaration, indexing, and operations such as assigning and accessing values. It also covers advanced features like custom index ranges, using loops with arrays, and aggregate algorithms for calculating sums, averages, maximums, and minimums. Additionally, it explains sorting algorithms such as Bubble Sort and Selection Sort, with examples and pseudocode for implementation.

Uploaded by

Londeka Jane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Introduction to Arrays 1

The document provides a comprehensive introduction to arrays, including their declaration, indexing, and operations such as assigning and accessing values. It also covers advanced features like custom index ranges, using loops with arrays, and aggregate algorithms for calculating sums, averages, maximums, and minimums. Additionally, it explains sorting algorithms such as Bubble Sort and Selection Sort, with examples and pseudocode for implementation.

Uploaded by

Londeka Jane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

I.

T LEGENDS IN THE MAKING

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.

Why Use Arrays?

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.

Example: An array to store temperatures for 30 days.

var
temperatures: array[1..30] of Integer;

Declaring Arrays

Arrays are declared by specifying:

 A name for the array.


 The data type of elements it will store.
 The range of indices defining the size of the array.

Syntax in pascal(delphi)

var
arrayName: array[lower..upper] of dataType;

Example: Declare an array to store the marks of 5 students.

var
studentMarks: array[1..5] of Integer;

Legendary 🔥
3

Understanding Array Indexing

Each position in an array is identified by an index. The index range is specified during
the declaration.

Visualization

Array studentMarks[1..5] can be visualized as

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)

Working with Arrays


Assigning Values to an array

Use the array name and the index to assign values.

studentMarks[1] := 87;
studentMarks[2] := 92;

Accessing Values from an array

To retrieve a value, refer to its index.

Memo.lines.add('Mark of student 1: ', studentMarks[1]);

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

// Assign values to the array


studentMarks[1] := 87;
studentMarks[2] := 92;
studentMarks[3] := 76;
studentMarks[4] := 88;
studentMarks[5] := 90;

// Calculate total
for i := 1 to 5 do
total := total + studentMarks[i];

// Calculate average
average := total div 5;

Memo.lines.add('The average mark is: ', average);


end.

Advanced Array Features


Custom Index Ranges

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

Arrays can use characters as indices:

var
gradeCount: array['A'..'F'] of Integer;

Default Values

You can initialize arrays with default values during declaration:

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

Using Loops with Arrays


Loops simplify operations on arrays, such as filling, modifying, or displaying elements.

Filling an Array with Input

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.

Displaying Array Values

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

Example: Character-Indexed Array

Index: A B C D E F
Value: 10 20 30 40 50 60

Legendary 🔥
6

Aggregate Algorithms for Arrays


Overview
Aggregate algorithms are used to calculate summarized information from arrays, such as:

 Sum: Total of all elements.


 Average: Mean value of elements.
 Maximum: Largest value in the array.
 Minimum: Smallest value in the array.

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

In , declare the array as follows:

var
temperatures: array[1..7] of Real; // Stores temperatures for 7 days

Calculating the Average Temperature

Algorithm

1. Initialize a variable sum to store the total temperature.


2. Loop through the array and add each temperature to sum.
3. Divide sum by the number of days to calculate the average.

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;

Memo.lines.add('The average temperature is: ', average:4:2, ' °C');


end.

Finding the Maximum Temperature

Algorithm

1. Initialize max to a very low value.


2. Loop through the array, comparing each value to max.
3. If a value is greater than max, update max.

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;

maxTemp := -999.0; // Initialize with a very low value

// Find maximum temperature


for i := 1 to 7 do
if temperatures[i] > maxTemp then
maxTemp := temperatures[i];

Memo.lines.add('The maximum temperature is: ', maxTemp:4:2, ' °C');


end.

Legendary 🔥
8

Finding the Minimum Temperature

Algorithm

1. Initialize min to a very high value.


2. Loop through the array, comparing each value to min.
3. If a value is less than min, update min.

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;

minTemp := 999.0; // Initialize with a very high value

// Find minimum temperature


for i := 1 to 7 do
if temperatures[i] < minTemp then
minTemp := temperatures[i];

Memo.lines.add('The minimum temperature is: ', minTemp:4:2, ' °C');


end.

Diagrams

Array Visualization

Day 1 2 3 4 5 6 7

Temperature 23.5 25.2 22.8 24.1 26.0 21.4 23.9


(°C)

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


Introduction

Bubble sort is a fundamental algorithm used to sort elements in an array by comparing


adjacent elements and swapping them if they are out of order. While other sorting
algorithms exist, Bubble Sort is often taught due to its simplicity and ease of
understanding.

How Bubble Sort Works

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:

 The largest unsorted element "bubbles" to its correct position.


 Subsequent passes focus on fewer elements as the sorted portion grows.

Example Scenario

Let’s sort the scores of a class quiz: [45, 32, 67, 23, 89].

Bubble Sort Pseudocode

1. Initialize a flag (swapped) to True to indicate if a swap occurred.


2. Repeat until no swaps are made:
o Set swapped to False.
o For each adjacent pair in the array:
 Compare the two elements.
 If the first element is greater than the second, swap them.
 Set swapped to True.
3. Stop when swapped remains False after a complete pass.

Code for Bubble Sort

This implementation sorts an array of integers in ascending order.

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;

// Output sorted array


Memo.lines.add(inttostr('Sorted array: '));
for i := 1 to 5 do
Memo.lines.add(inttostr (scores[i], ' '));
end.

Visualization

Below is a step-by-step visualization of sorting [45, 32, 67, 23, 89]:

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

Modifications to Bubble Sort

1. Descending Order: Change the condition from > to < in the comparison:

if scores[i] < scores[i + 1] then

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

Selection Sort Algorithm


Introduction

Selection Sort is a straightforward sorting algorithm used to organize elements in an


array. The algorithm works by repeatedly selecting the smallest (or largest, depending on
the order) element from the unsorted portion of the array and swapping it with the first
element of that portion.

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.

How Selection Sort Works

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

Pass 4: The remaining two elements are already sorted.

Final sorted array: [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

Here is a implementation of Selection Sort to sort an array of integers in ascending order.

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;

// Display the sorted array


Memo.lines.add('Sorted array: ');
for i := 1 to 5 do
Memo.lines.add(inttostr(prices[i], ' ');
Memo.lines.add;
end.

Modifications

1. Descending Order:
o Change the comparison from < to > in the if condition:

if prices[j] > prices[minIndex] then

2. Different Data Types:


o For sorting real numbers or strings, adjust the array's data type and the
temp variable.

Key Points and Best Practices

 Efficiency: Selection Sort has a time complexity of O(n2)O(n^2)O(n2) for large


datasets, making it less efficient compared to advanced algorithms like Merge Sort.
 Simplicity: It is easy to implement and understand, which is ideal for learning
sorting concepts.
 Best Use Case: Suitable for small datasets where simplicity outweighs efficiency
concerns.

Legendary 🔥
16

Linear Search Algorithm


Introduction

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.

How Linear Search Works

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

Array Example: [1023, 1001, 1045, 1010, 1032]


Target Value: 1010

Iterations:

1. Check index 0: 1023 ≠ 1010.


2. Check index 1: 1001 ≠ 1010.
3. Check index 2: 1045 ≠ 1010.
4. Check index 3: 1010 = 1010 → Target found at index 3.

Legendary 🔥
17

Pseudocode

found ← false
index ← 0

while not found and index < array_length do


if array[index] = target then
found ← true
position ← index
else
index ← index + 1

if found then
print "Value found at position ", position
else
print "Value not found in the array"

Code

Here is a implementation of Linear Search to search for a specific ID in an array.

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;

// Input the target value


Target:=strtoint(inputbox(‘Student ID’,'Enter the student ID to
search for: ',’’)

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

Memo.lines.add('Student ID ', target, ' found at position ',


position)
else
Memo.lines.add('Student ID ', target, ' not found in the array');
end.

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:

 Step 1: Check 1023 (index 0) → No match.


 Step 2: Check 1001 (index 1) → No match.
 Step 3: Check 1045 (index 2) → No match.
 Step 4: Check 1010 (index 3) → Match found!

After Search: ( Target Found )( Index = 3 )

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.

Enhancements and Modifications

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

Binary Search in Arrays


Introduction to Binary Search

Binary Search is an efficient algorithm to find a value in a sorted array by repeatedly


dividing the search range in half. Unlike linear search, binary search requires the data to
be sorted beforehand. Its efficiency makes it especially useful for large datasets.

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.

How Binary Search Works

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

Initial Array: [101, 203, 305, 407, 509, 611]


Target: 305

Step Lower Midpoint Upper Value at Midpoint Comparison Result

1 0 2 5 305 Match Found

Pseudocode

function binarySearch(array, target):


lower ← 0
upper ← array.length - 1
found ← false

Legendary 🔥
20

while lower <= upper and not found:


mid ← (lower + upper) div 2
if array[mid] = target:
found ← true
position ← mid
else if array[mid] < target:
lower ← mid + 1
else:
upper ← mid - 1

if found:
return position
else:
return -1

Implementation

Below is a implementation of Binary Search to find a specific book ID in a library


system.

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;

// Input the target value


Memo.lines.add(inttostr('Enter the book ID to search for: ');
ReadLn(target);

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

Lower = 1, Upper = 6, Midpoint = (1+6) div 2 = 3


Array = [101, 203, 305, 407, 509, 611]

Midpoint

Comparison: bookIDs[3] = 305 → Match Found!

Key Features

1. Efficiency:
o Time Complexity: O(log⁡n)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

1. Find Closest Value:


o Modify the algorithm to find the closest value if the target is not present.
2. Recursive Implementation:
o Binary Search can also be implemented using recursion for cleaner code in
some cases.

Legendary 🔥
22

Specific Indices in Arrays


Introduction

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.

Advantages of Specific Indices

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.

Example: Voting System

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

Initial State (No votes cast yet):

Index: 1 2 3 4 5
Votes: 0 0 0 0 0

After Votes Are Cast (Votes for candidates 1, 2, 2, 3, and 1):

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):
',’’));

if (candidate >= 1) and (candidate <= 5) then


Inc(votes[candidate]) // Increment vote count for the chosen
candidate
else
Memo.lines.add('Invalid candidate number!');
end;

// Display the results


Memo.lines.add('Vote count:');
for i := 1 to 5 do
Memo.lines.add('Candidate ', inttostr(i), ': ', inttostr(votes[i]),
' votes');
end.

Working with Ranges

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

Example: Categorizing Ages into Groups

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;

// Input ages and categorize them


for i := 1 to 10 do
begin
Memo.lines.add(inttostr('Enter age: ');
ReadLn(age);

if (age >= 1) and (age <= 25) then


Inc(ageGroups[1])
else if (age >= 26) and (age <= 50) then
Inc(ageGroups[2])
else if (age >= 51) and (age <= 75) then
Inc(ageGroups[3])
else if (age >= 76) then
Inc(ageGroups[4])
else
Memo.lines.add('Invalid age entered!');
end;

// Display age group counts


Memo.lines.add('Age Group Counts:');
Memo.lines.add('1-25: '+strtoint(ageGroups[1]));
Memo.lines.add('26-50: '+ strtoint(ageGroups[2]));
Memo.lines.add('51-75: '+ strtoint(ageGroups[3]));
Memo.lines.add('76+: '+ strtoint(ageGroups[4]));
end.

Diagram

Initial State (Before categorization):

Group: 1-25 26-50 51-75 76+


Count: 0 0 0 0

Legendary 🔥
25

After Categorization (Sample Input):

Ages: 15, 34, 72, 18, 49, 55, 77, 19, 66, 80

Group: 1-25 26-50 51-75 76+


Count: 3 2 3 2

Dice Throwing Example

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;

// Simulate 50 dice rolls


Randomize;
for i := 1 to 50 do
begin
roll := Random(6) + 1; // Generate a number between 1 and 6
Inc(diceResults[roll]); // Increment the corresponding result
end;

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

1. Initialization: Always initialize arrays before using them to avoid unintended


behavior.
2. Validation: Validate indices before accessing an array to prevent runtime errors.
3. Efficiency: Use specific indices when each index directly maps to a meaningful
category.

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.

Scenario: Inventory Management

Imagine you are managing an inventory system for a store. Two arrays are used:

 One array (itemNames) holds the names of items.


 Another array (itemQuantities) holds the corresponding quantities in stock.

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.

2. Finding Corresponding Values

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.

Example: Adding and Finding Items

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]));

// Adding a new item


NewItem:=inputbox(‘Item’,'Enter new item name: ',’’);

NewQuantitty:=(inttostr(inputbox('Quantity’,’Enter quantity: ',’’));


Inc(itemCount);
itemNames[itemCount] := newItem;
itemQuantities[itemCount] := newQuantity;

Legendary 🔥
28

// Finding item with the highest and lowest quantity


maxIndex := 1;
minIndex := 1;

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]);

Memo.lines.add('Item with highest stock: ', itemNames[maxIndex], '


(', itemQuantities[maxIndex], ')');
Memo.lines.add('Item with lowest stock: ', itemNames[minIndex], ' (',
itemQuantities[minIndex], ')');
end.

Sorting Parallel Arrays

To sort parallel arrays, the sorting logic must operate on all related arrays to maintain
their relationship.

Example: Sorting by Quantity

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

// Sorting by quantity (ascending)


for i := 1 to itemCount - 1 do
for j := i + 1 to itemCount do
begin
if itemQuantities[i] > itemQuantities[j] then
begin
// Swap quantities
tempQuantity := itemQuantities[i];
itemQuantities[i] := itemQuantities[j];
itemQuantities[j] := tempQuantity;

// Swap names to maintain relationship


tempName := itemNames[i];
itemNames[i] := itemNames[j];
itemNames[j] := tempName;
end;
end;

// Display sorted inventory


Memo.lines.add('Sorted Inventory:');
for i := 1 to itemCount do
Memo.lines.add(itemNames[i], ': ', itemQuantities[i]);
end.

Diagram of Sorting

Before Sorting

Index 1 2 3 4
ItemNames Pen Notebook Erasor Pencil
ItemQuantities 50 30 20 15

After Sorting (Ascending by Quantity)

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

 Inventory Management: Item names and quantities.


 Student Data: Names, marks, and grades.
 Product Details: Product names, prices, and stock levels.

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.

Loading Data from a Text File into an Array

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.

Scenario: Product Inventory Management

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

We want to load this data into two parallel arrays:

 productNames (for storing the names of the products)


 productPrices (for storing the prices of the products)

The goal is to load each product's name into productNames and its corresponding price
into productPrices.

Diagram

Initial Data in Text File (products.txt)

Legendary 🔥
31

Apple, 1.25
Banana, 0.75
Orange, 1.50

After Loading into Arrays

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.

Code: Loading Data into 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;

// Try to open the file


AssignFile(productFile, 'products.txt');
Reset(productFile);

// Read data line by line


while not Eof(productFile) do
begin
ReadLn(productFile, line);

// Increment size to store new data


Inc(size);

// Find the position of the comma (to separate name and price)
commaPos := Pos(',', line);

// Extract the product name (everything before the comma)


productName := Copy(line, 1, commaPos - 1);

// Extract the product price (everything after the comma)


productPrice := StrToFloat(Copy(line, commaPos + 1, Length(line) -
commaPos));

// Store the product name and price in the arrays


productNames[size] := productName;
productPrices[size] := productPrice;
end;

// Close the file


CloseFile(productFile);

// Display the loaded data


Memo.lines.add('Loaded Products and Prices:');
for i := 1 to size do
begin
Memo.lines.add('Product: ', productNames[i], ', Price: ',
productPrices[i]:0:2);
end;
end.

Explanation of the Code

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.

Handling Parallel Arrays

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.

Diagram of Parallel Arrays

After Loading into Arrays

Index 1 2 3
productNames Apple Banana Orange
productPrices 1.25 0.75 1.50

Here, productNames[1] (Apple) corresponds to productPrices[1] (1.25), and so on.

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:

1. Use file handling functions to read data from a text file.


2. Use Pos and Copy functions to extract data from each line.
3. Update arrays in sync when dealing with parallel arrays.
4. Always ensure that the data in one array corresponds correctly to the data in
another array when using parallel arrays.

Legendary 🔥
35

Legendary 🔥

You might also like