Algorithms and Programming
Algorithms and Programming
programming
Phone : 695744632
[email protected]
September 2025
Table of Contents
1. Introduction to Programming Logic and Coding Languages
2. Basic Structures in Pascal
3. Functions and Procedures
4. Arrays and Linear Data Structures
5. Algorithmic Approaches
6. Fundamental Algorithms
7. Practical Exercises and Applications
P a g e 1 | 65
CHAPTER 1: Introduction to
Programming Logic and Coding
Languages
Programming logic, also called Algorithmic, is a method for solving
problems following a determined sequence of operational
rules. It is the description of a process. It corresponds to a sequence of
steps whose execution achieves a set goal. Its implementation solves a
given problem.
1. Introduction to Algorithms
1.1 What is an Algorithm?
It is essential for:
Statement of problem:
• Input: A sequence of n numbers <a1, a2, …, an>
• Output: A reordering of the input sequence <a´1,
a´2, …, a´n> so that a´i ≤ a´j whenever i < j
Instance: The sequence <5, 3, 2, 8, 3>
Algorithms:
• Selection sortP a g e 2 | 65
• Insertion sort
• Merge sort
• (many others)
What do we want to do? What results do we want to obtain?
How to do it? What variables, types, operations, and
processing should be applied to the base data to obtain
the required results?
o The action is broken down into sub-actions.
o What abstract method can be used to perform the action?
o What decomposition model should we use to perform this
action using the chosen method?
o What objects are needed to allow this decomposition?
(variables, types, domains, etc.)
Are we doing what we intended? Proof of validity.
The design of a program that must solve a given problem should follow
the following steps:
Problem Statement
Analysis P a g e 3 | 65
Algorithm
Coding
Note that each program (algorithm) must have a name and must have
three parts: Header, Declarative Part, and Program Body.
The analysis phase and the translation phase are intellectual human
operations, while the compilation and execution phases are performed
automatically by the machine.
A semantic error is a fault due to a poor design of the method
followed to solve the problem (analysis phase); it is related to logic.
Here, it is a program that does not meet the client's or user's
expectations, so the algorithm must be corrected from the analysis
phase.
A syntax error is a spelling or grammar mistake. It is made in the
coding phase and is reported by the compiler when it cannot interpret
an instruction from the source program to translate it into machine
language (assembly language). Here, the program cannot execute (no
executable program).
Every algorithm has the following three parts: the algorithm's name,
the declarative part, and the algorithm's body.
Declarative Part: This part will contain the declaration of all the
variables we will use in the algorithm.
Algorithm Body: The body of an algorithm includes:
initialization (assigning starting values to different variables),
execution (applying the processing or executing the different
P a g e 4 | 65
primitive actions of the problem), and returning results
(displaying or returning the obtained results).
ALGORITHM NAME
DECLARATIVE PART
EXECUTION
Algorithm Body
RETURNING
RESULTS
ALGORITHM AlgorithmName
{ Declarative Part
Start
{ Algorithm Body
Stop
Example:
P a g e 5 | 65
Example:
Read grade1,
grade2, grade3
P a g e 6 | 65
Pascal Program:
program CalculateAverage;
P a g e 7 | 65
uses CRT;
{ This program calculates the average of three grades entered by the user. It
illustrates the use of variables, constants, input/output, and basic calculations. }
const
coef1 = 3; coef2 = 2; coef3 = 5; { Assigning values to different constants }
var
grade1, grade2, grade3, Avg: real; { Declaring variables for grades and
average }
begin
ClrScr;
writeln('Enter three grades: '); { Asks the user to enter the grades }
readln(grade1, grade2, grade3); { Reads the three grades }
Avg := (grade1 * coef1 + grade2 * coef2 + grade3 * coef3) / (coef1 + coef2 + coef3); {
Calculates the average }
writeln('The average is: ', Avg:2:2); { Displays the average with 2
decimal places }
ReadKey;
end.
P a g e 8 | 65
In general, each programming language is linked to a particular type of
programming:
Makup Language)
Brute Force: Tests all possible solutions until the correct one is
found. Simple but often inefficient for large problems.
Divide and Conquer: Divides the problem into sub-problems,
solves them recursively, and then combines the results (e.g.,
merge sort, quicksort).
Dynamic Programming: Optimizes recursive calls by storing
intermediate results in a table to avoid redundant calculations
(e.g., 0-1 knapsack problem).
Greedy: Makes locally optimal decisions at each step, without
guaranteeing global optimality (e.g., activity selection, fractional
knapsack).
Backtracking: Explores all possible solutions by backtracking if
a path does not lead to a solution (e.g., N-queens problem).
Branch and Bound: Used for combinatorial optimization
problems. It explores the solution space by eliminating non-
promising branches (e.g., traveling salesman problem).
P a g e 10 | 65
Transformation and Conquest: Transforms a complex
problem into a known, already solved problem (e.g., finding the
median by first sorting the list).
Iterative Improvement: Gradually improves an initial solution
(e.g., simplex algorithm in linear programming).
3. Design Approaches
Top-Down Approach: Breaks down a complex problem into
simpler sub-problems until elementary solutions are obtained.
Bottom-Up Approach: First solves the simplest sub-problems,
then combines them to solve the overall problem.
4. Other Classifications
Randomized Algorithms: Use random choices to speed up
resolution (e.g., randomized quicksort).
Complexity Classification: Algorithms are analyzed based on
their execution time (e.g., O(n), exponential). This allows
comparing their theoretical efficiency.
Classification by Research Domain: Each domain (operations
research, artificial intelligence, machine learning) has its own
specialized algorithms (e.g., sorting algorithms for databases,
learning algorithms for AI).
Enumeration and Backtracking: Used in artificial intelligence
to explore complex solution spaces.
Summary
Data Type:
P a g e 12 | 65
This can be:
Input data;
An intermediate calculation result.
The final result of a calculation.
Example:
Var A : Interger
VARIABLES
Ex1 : Variable A of Integer
A
EST_DU_TYPE
NOMBRE
P a g e 13 | 65
Data Structure:
Data Structure = Organized Data + Operations on Data
Structures
2. Program Organization
The algorithm of a program is organized into several parts:
Definition of Types
Declaration of Constants
Declaration of Variables
P a g e 14 | 65
Definition of Functions and Procedures
Definition of the Main Program
Procedure without
parameter: .................................................................... Ex:
Clear_Screen
3. Assignment
An assignment consists of assigning a value to a variable.
A
constant. ......................................................................................
Ex: area ← 40
Another variable. ......................................................... Ex: Data ←
StoredValue
The result of a function. ................................................ Ex: result
← square (number)
A calculation involving these different elements. ... Ex: area ← (PI
* Square (Diameter)) / 4
4. Operators - Conditions
4.1 Operators
P a g e 17 | 65
Operators allow constructing an expression to perform a calculation or
comparison.
P a g e 18 | 65
Practical Exercise: Write an algorithm to display the values (the
number 10, pi=3.14, the letter A, the string "Hello, world") assigned to
three variables of integer, decimal, character, and string types.
program VariablesAndDataTypes;
uses crt;
uses SysUtils;
var
integerVar: Integer;
realVar: Real;
charVar: Char;
stringVar: String;
begin
ClrScr;
integerVar := 10;
realVar := 3.14;
charVar := 'A';
stringVar := 'Hello, World!';
ReadKey;
end.
4.2 Conditions
P a g e 19 | 65
Practical Exercise: Write an algorithm to display the result of the
sum, difference, product, quotient, and remainder of the division
between two values a and b entered from a keyboard.
program OperatorsAndExpressions;
uses crt;
var
a, b, sum, difference, product, quotient: Integer;
begin
ClrScr;
a := 10;
b := 5;
sum := a + b;
difference := a - b;
product := a * b;
quotient := a div b;
delay(10000);
end.
5. Elementary Instructions
5.1 Input Instructions
These are input instructions that allow retrieving a value entered from
an input device (keyboard, mouse, etc.). The syntax for use is as
follows:
Syntax:
READ(Identifier) or INPUT(Identifier)
The identifier is an object previously declared in the VAR section.
Example:
READ(grade1)
READ(grade2)
P a g e 20 | 65
Or
READ(grade1, grade2)
Or even
INPUT(grade1, grade2)
Example:
Complete Example:
program InputOutputOperations;
var
P a g e 21 | 65
name: String;
age: Integer;
begin
writeln('Enter your name: ');
readln(name);
writeln('Enter your age: ');
readln(age);
writeln('Your name is ', name, ' and you are ', age, ' years old.');
end.
6. Algorithmic Structures
Algorithmic structures are divided into 3 categories:
Flowchart Syntax:
Action1
Action2
...
ActionN
Algorithm: productof2numbers
Step1 Start
Step2 initialize p=0 ~ product result ~
Step3 Input a, b ~ operands ~
Step4 p←a*b
Step5 Display(p)
Step6 Stop.
P a g e 22 | 65
Applied Exercise: Write the algorithm to swap the values of two
variables: Initially, a = 3 and b = 7. Subsequently, b = 3 and a
receives 7.
Flowchart Syntax:
Condition If Condition
Actions
Then Actions
EndIf
P a g e 23 | 65
A condition is tested to determine which action or group of actions
should be executed.
Flowchart Syntax:
Condition If Condition
Actions1 Actions2
Then
Actions1
Else
Actions2
EndIf
Pascal Program:
program DecisionMakingStructures;
var
num: Integer;
begin
writeln('Enter a number: ');
readln(num);
P a g e 24 | 65
if num > 0 then
writeln(num, ' is positive.')
else if num < 0 then
writeln(num, ' is negative.')
else
writeln(num, ' is zero.');
end.
Algorithm: EvenOrOdd
Variables: number: integer
Begin
Read(number)
If number % 2 = 0 Then
Display("The number is even.")
Else
Display("The number is odd.")
EndIf
End
Pascal Program:
program EvenOrOdd;
var
number: integer;
begin
writeln('Enter a number: ');
readln(number);
if number mod 2 = 0 then
writeln('The number is even.')
else
writeln('The number is odd.');
end.
Algorithm: FindMaximum
Step1 Start
Step2 let max ~ result ~
Step3 Read(a, b)
Step4 If a > b Then
Step5 let max ← a
P a g e 25 | 65
Step6 Display('x is negative')
Step7 Else
Step8 let max ← b
Step9 EndIf
Step10 Write("The maximum is: ", max)
Step11 Stop.
Pascal Program:
program FindMaximum;
var
a, b, max: integer;
begin
writeln('Enter two numbers: ');
readln(a, b);
if a > b then
max := a
else
max := b;
end.
Flowchart Syntax:
P a g e 26 | 65
Other : ActionsDéfaut
EndCase
Flowchart Syntax:
Repeat
Actions
Actions
Until Condition
Condition
P a g e 27 | 65
Note: The condition is checked after the actions. They are therefore
executed at least once.
Example: Repetitive execution of a program
Algorithm: Repetitive execution of a program
Step1 Start:
Step2 let p0 ~ product result ~
let c of character ~ user response ~
Step3 Repeat
Step4 Read(a, b)
Step5 p←a*b
Step6 Display(p)
Step7 Write('Another calculation? No press N; Yes
any other key')
Step8 Input(c)
Step9 Until c = 'N'
Step10 Stop.
program PINCodeChecker;
uses crt;
var
i, pin: Integer;
begin
ClrScr;
writeln('--------------------------');
writeln(' Set PIN Code: ');
writeln('--------------------------');
readln(codepin);
i := 0;
repeat
writeln('----------------------------');
writeln(' Enter your PIN Code: 🡪 ');
writeln('----------------------------');
readln(pin);
i := i + 1;
until pin = codepin;
writeln('----------------------------');
writeln(' Number of Trials: ', i);
writeln('----------------------------');
P a g e 28 | 65
delay(20000);
end.
Flowchart Syntax:
While Condition
Condition Do Actions
Actions EndDo
Begin
While Not (KeyPressed)
Do
Display('Waiting')
EndDo
End
program Counting;
uses crt;
uses SysUtils;
var
i: Integer;
begin
ClrScr;
i := 1;
P a g e 29 | 65
while i <= 10 do
begin
writeln('While loop iteration: ', i);
i := i + 1;
end;
delay(15000);
end.
Flowchart Syntax:
Note: The initial (Value1) and final (Value2) values are included.
Variable:
i: integer ~ loop counter ~
Begin
For i From 1 To 80
Do
Display('*')
EndDo
End
P a g e 30 | 65
program CalculateFactorial;
var
n, i, factorial: integer;
begin
writeln('Enter a number: ');
readln(n);
factorial := 1;
for i := 1 to n do
factorial := factorial * i;
program MultiTables;
uses crt;
uses SysUtils;
var
i, j: Integer;
begin
ClrScr;
for i := 1 to 12 do
begin
writeln('Multiplication Table: ', i);
writeln('------------------------');
for j := 1 to 10 do
begin
writeln(i, 'x', j, '=', i*j);
j := j + 1;
end;
Inc(i);
end;
delay(15000);
end.
Inc Inc
Loop 2 j j . . J
1 2
. . 1
i
0
1
Loop 1
..
..
..
I
P a g e 31 | 65
2
Note: This algorithmic structure can actually be replaced by a
WHILE ... DO ... structure.
1. Start
2. Let i ← 1~ loop counter ~
3. While i ≤ 80
4. Do
5. Display('*')
6. i ← i + 1 ~ Increment by 1 ~
7. EndDo
8. End
TotalPay Count
Payment Number Pay Initial Final Initial Fin
al
P a g e 32 | 65
2nd payment 50, 000 100, 150, 000 1 2
000
TotalPay
TotalPay + Pay
6.4.2 Counters
These are variables that calculate and determine the number of times
an action or processing is executed during processing. Counters evolve
according to a step.
Example:
Count Count
+1
TotalPay ← 0
P a g e 33 | 65
Count ← 0
7. Subprograms
The main program is therefore the set that executes when the
application is launched and is responsible for requesting the execution
of the instructions in the subprogram.
7.1 Functions
Role of Functions:
Algorithm:
P a g e 34 | 65
Pascal Program:
program SumFunction;
{
This program uses a function to calculate the sum of two numbers.
It shows how to declare, define, and call a function in Pascal.
}
var
num1, num2, result: integer; { Variables to store numbers and result }
begin
Sum := a + b; { Calculates the sum and returns it }
end;
begin
writeln('Enter two numbers:'); { Asks the user to enter two numbers }
readln(num1, num2); { Reads the two numbers }
result := Sum(num1, num2); { Calls the Sum function and stores the result }
writeln('The sum is: ', result); { Displays the result }
end.
P a g e 35 | 65
Application of Recursion:
Execution:
Algorithm Solution:
Algorithm Combination
Start
let m, n as byte
let Comb as integer
Procedure Factorial(X: byte, Fact: integer): integer
let i as byte
Begin
If (X = 1) or (X = 0) Then
Fact ← 1
P a g e 36 | 65
Else
Fact ← 1
For i ← 1 to X Do
Fact ← Fact * i
EndFor i
EndIf
End Procedure
Read m, n
If (m >= n) and (n >= 1) Then
Comb ← Factorial(m, 1) / Factorial(n, 1) * Factorial(m-
n, 1)
Write Comb
EndIf
END.
Pascal Solution:
Program Combination;
Begin
Fact := 1;
For I := 1 to n Do
Factorial := Fact;
End;
Begin
Write('Enter two integers m and n');
Readln(m, n);
Write(Factorial(m) / Factorial(n) * Factorial(m-n));
End.
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2) for n > 1
Example:
program DynamicFibonacci;
{
This program calculates the Fibonacci sequence with dynamic programming.
It shows how to use memoization to avoid unnecessary recalculations.
}
const
MAX = 100; { Maximum size of the memoization table }
var
memo: array[0..MAX] of integer; { Table to store intermediate results }
n: integer; { Number for which we want to calculate the Fibonacci sequence }
begin
{ If the result is already calculated, return it directly }
if memo[n] <> -1 then
Fibonacci := memo[n]
{ Base case: Fibonacci(0) = 0 and Fibonacci(1) = 1 }
else if n <= 1 then
Fibonacci := n
{ Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2) }
else
begin
memo[n] := Fibonacci(n-1) + Fibonacci(n-2); { Store the result in the table }
Fibonacci := memo[n]; { Return the result }
end;
end;
begin
{ Initialize the memoization table with -1 (not calculated) }
for n := 0 to MAX do
memo[n] := -1;
P a g e 39 | 65
writeln('Enter a number:');
readln(n); { Read the number }
writeln('Fibonacci(', n, ') = ', Fibonacci(n)); { Display the result }
end.
7.3 Procedures
Role of Procedures:
Algorithm:
Pascal Program:
program WelcomeProcedure;
{
This program uses a procedure to display a welcome message.
It shows how to declare, define, and call a procedure in Pascal.
}
var
userName: string; { Variable to store the user's name }
P a g e 40 | 65
procedure WelcomeMessage(name: string);
{
This procedure displays a personalized welcome message.
Parameters: name: the name of the person to greet
}
begin
writeln('Hello, ', name, '!'); { Displays the welcome message }
end;
begin
writeln('Enter your name:'); { Asks the user to enter their name }
readln(userName); { Reads the name }
WelcomeMessage(userName); { Calls the WelcomeMessage procedure }
end.
PRACTICAL EXERCISES
Exercise 1:
Exercise 2:
Synthesis Exercise:
P a g e 41 | 65
CHAPTER 4: Arrays and Linear Data
Structures
I. ARRAYS
Indices are pointers that allow locating the different cells of an array
to facilitate its exploitation. The index is characterized by the following
elements:
A name
A starting value (initial value)
A final value: it determines the size of the array, i.e., the number
of cells
Its type
A name
A minimum index value
A maximum index value (array size)
The type of data stored in the array.
a) First Method:
b) Second Method:
or
P a g e 43 | 65
II. ONE-DIMENSIONAL ARRAYS
These are arrays that use only one index for their exploitation. In this
case, the processing is done linearly in the horizontal or vertical
direction.
Algorithm creation1
start
let averages [1..10]: ARRAY OF real
let i of integer
For i From 1 To 10 Do
Write('Enter The Average Of Student: ', i)
Read(Averages[i])
i←i+1
End For
End.
Role of Arrays:
Algorithm:
Algorithm SumArray
Process:
P a g e 44 | 65
1. sum = 0
2. For i = 1 to 5 Do sum = sum + array[i] Output: sum
End Algorithm
Pascal Program:
program SumArray;
{
This program calculates the sum of the elements of an array.
It shows how to declare, fill, and traverse an array in Pascal.
}
var
array: array[1..5] of integer; { Declaration of an array of 5 integers }
i, sum: integer; { Variables for index and sum }
begin
{ Filling the array }
for i := 1 to 5 do
begin
writeln('Enter element ', i, ':');
readln(array[i]); { Reads each element of the array }
end;
Sum
Product
Average of cells
Search for minimum and maximum
Sorting array values
Deleting an element
P a g e 45 | 65
Algorithm:
Pascal Program:
program SumArray;
var
tab: array[1..5] of integer; // Array of 5 integers
i, sum: integer;
begin
// Initializing the array
tab[1] := 10;
tab[2] := 20;
tab[3] := 30;
tab[4] := 40;
tab[5] := 50;
Algorithm:
Pascal Program:
program ProductArray;
P a g e 46 | 65
var
tab: array[1..5] of integer;
i, product: integer;
begin
// Initializing the array
tab[1] := 2;
tab[2] := 3;
tab[3] := 4;
tab[4] := 5;
tab[5] := 6;
Algorithm:
Pascal Program:
program AverageArray;
P a g e 47 | 65
var
tab: array[1..5] of integer;
i, sum, average: integer;
begin
// Initializing the array
tab[1] := 10;
tab[2] := 20;
tab[3] := 30;
tab[4] := 40;
tab[5] := 50;
Algorithm:
1. Initialize min and max with the first element of the array.
2. Traverse each element of the array.
3. If an element is smaller than min, update min.
4. If an element is larger than max, update max.
5. Display min and max.
P a g e 48 | 65
Pascal Program:
program MinMaxArray;
var
tab: array[1..5] of integer;
i, min, max: integer;
begin
// Initializing the array
tab[1] := 15;
tab[2] := 7;
tab[3] := 22;
tab[4] := 3;
tab[5] := 19;
program SortArray;
var
tab: array[1..5] of integer;
i, j, temp, minIndex: integer;
begin
// Initializing the array
tab[1] := 22;
tab[2] := 7;
tab[3] := 15;
tab[4] := 3;
tab[5] := 19;
// Selection sort
for i := 1 to 4 do
begin
minIndex := i;
for j := i + 1 to 5 do
if tab[j] < tab[minIndex] then
minIndex := j;
// Swapping elements
temp := tab[i];
tab[i] := tab[minIndex];
tab[minIndex] := temp;
end;
Bubble Sort
P a g e 50 | 65
Educational: Good for learning the basics of sorting algorithms.
Algorithm:
Algorithm BubbleSort
Process:
End Algorithm
Pascal Program:
program BubbleSort;
{
This program sorts an array using bubble sort.
It shows how to implement a simple sorting algorithm.
}
var
array: array[1..5] of integer; { Array to sort }
i, j, temp: integer; { Variables for loops and swapping }
begin
{ Reading array elements }
for i := 1 to 5 do
begin
writeln('Enter element ', i, ':');
readln(array[i]);
end;
{ Bubble sort }
for i := 1 to 4 do { Traverse the array }
for j := 1 to 5-i do { Compare adjacent elements }
if array[j] > array[j+1] then { If the current element is greater than the next }
begin
{ Swap elements }
temp := array[j];
array[j] := array[j+1];
array[j+1] := temp;
end;
Algorithm:
Pascal Program:
program DeleteElement;
var
tab: array[1..5] of integer;
i, pos: integer;
begin
// Initializing the array
tab[1] := 10;
tab[2] := 20;
tab[3] := 30;
tab[4] := 40;
tab[5] := 50;
// Shifting elements
for i := pos to 4 do
tab[i] := tab[i + 1];
Role of 2D Arrays:
P a g e 52 | 65
Matrix Representation: Useful for mathematical calculations
and grids.
Data Organization: Allows structuring data in rows and
columns.
Algorithm:
Algorithm Print2DArray
Process:
End Algorithm
Pascal Program:
program Print2DArray;
{
This program displays the elements of a 2D array.
It shows how to declare, fill, and traverse a two-dimensional array.
}
var
array: array[1..2, 1..2] of integer; { Declaration of a 2x2 2D array }
i, j: integer; { Variables for indices }
begin
{ Filling the 2D array }
for i := 1 to 2 do
for j := 1 to 2 do
begin
writeln('Enter element [', i, ',', j, ']:');
readln(array[i, j]); { Reads each element of the array }
end;
P a g e 53 | 65
1. Variables and Data Types
Role of Variables:
Unlike arrays, which are data structures where all elements are
of the same type, records are data structures where elements
can be of different types and relate to the same entity. The
elements that make up a record are called fields.
We want to calculate and display the averages of two grades (TD and
TP) obtained by students in a program. We also want to memorize the
name and first name of each student in a class of 20 students.
Solution 1:
Solution 2:
Use a single array that integrates the different data types since
each student is characterized by a name, a first name, a TD
grade, and a TP grade. Hence the concept of a record.
P a g e 54 | 65
Field1 Field2 Field3 Field4 Field1 Field2 Field3 Field4
Type1 Type2 Type3 Type4 Type1 Type2 Type3 Type4
1st record 2nd record
P a g e 55 | 65
Example:
Example:
<variable_name.field>
Example:
Student.Name
Student.FirstName
Student.TD
Student.TP
P a g e 56 | 65
Exercise: Declare a variable to store the name, age, and height of 4
students.
Pascal Program:
program SimpleStudentRecord;
uses crt;
type
Student = Record
name: String[50];
average: Real;
age: Integer;
end;
var
students: array[1..4] of Student;
i: Integer;
begin
ClrScr;
for i := 1 to 4 do
begin
write('Enter student name ', i, ': ');
readln(students[i].name);
write('Enter student age ', i, ': ');
readln(students[i].age);
write('Enter student average ', i, ': ');
readln(students[i].average);
end;
readkey;
end.
P a g e 57 | 65
V. FILE STRUCTURES
1. Introduction
2. Definition
3. File Organization
P a g e 58 | 65
a. Sequential Organization
In this case, all records in the file are traversed from the first to the
last, one after the other. That is, to access the data of order N, you
must first traverse the previous N-1 data. This is also called linear
organization.
Sequential access
Direct access
a. Definition
A file is said to have sequential access if accessing its nth index record
requires going through the previous n-1 records. In this case, records
are written one after the other, and reading always starts with the first,
then the next, until the last.
P a g e 59 | 65
Read Instruction:
READ STUDENT copies data from the physical medium to the central
memory, the information of a student based on two previously
declared variables that must receive the read data (NameS, BirthY).
Write Instruction:
Rewrite Instruction:
Delete Instruction:
c. File Declaration
First Method:
Second Method:
P a g e 60 | 65
TYPE file_type_name = FILE
Record_Type_Name = RECORD
Field1: type1
Field2: type2
Fieldn: type n
END RECORD
P a g e 61 | 65
file variable name)
CLOSE a file (always do this when | CLOSE (logical name)
it has been opened)
Boolean test function to check if IF End_OF_FILE (logical name)
the end of the file is reached Then action1
Else action2
ENDIF
Note:
Simple Algorithm
Objective:
Write text to a file, then read it back and display it on the screen.
Steps:
program SimpleFileManagement;
var
MyFile: text; // Variable to manipulate the file
TextToRead: string; // Variable to store the read text
begin
{ Step 1: Opening the file for writing }
assign(MyFile, 'myfile.txt');
rewrite(MyFile);
Step-by-Step Explanations
1. Declaration:
3. Writing:
P a g e 63 | 65
writeln(MyFile, 'Hello...'): Writes a line to the file.
4. Closing:
close(MyFile): Closes the file after writing.
while not eof(MyFile) do: Loops until the end of the file.
readln(MyFile, TextToRead): Reads a line from the file.
writeln('File content: ', TextToRead): Displays the line read.
7. Final Closing:
4. Expected Result:
P a g e 64 | 65