Module 3: Advanced Pascal Programming Concepts
Lesson 6: Arrays
Objective: Teach learners how to work with arrays in Pascal, including declaring, accessing, and modifying array elements.
Understanding Arrays:
An array is a collection of variables that are accessed with an index number. All elements in an array are of the same data type. Arrays allow you to store multiple values in a single variable, making it easier to manage data in your programs.
Declaring an Array:
To declare an array in Pascal, you specify the data type of the elements and the range of indices. Here’s an example:
var
numbers: array[1..5] of Integer;
In this example:
- numbers: is the name of the array.
- array[1..5] of Integer: declares an array of integers with 5 elements, indexed from 1 to 5.
Accessing Array Elements:
You can access individual elements of an array using their index. The index must be within the declared range. Here’s how you can access and assign values to array elements:
numbers[1] := 10;
numbers[2] := 20;
writeln(numbers[1]); // Outputs: 10
In this example:
- numbers[1] := 10: assigns the value 10 to the first element of the array.
- numbers[2] := 20: assigns the value 20 to the second element of the array.
- writeln(numbers[1]): prints the value of the first element (10) to the console.
Iterating Over an Array:
You can use a loop to iterate over the elements of an array. This is particularly useful when you need to perform the same operation on each element:
var
i: Integer;
begin
for i := 1 to 5 do
writeln('Element ', i, ': ', numbers[i]);
end;
In this example:
- for i := 1 to 5 do: loops through each index of the array.
- writeln('Element ', i, ': ', numbers[i]): prints the index and value of each element.
Exercises:
- Declare an array of 10 integers. Assign values to the first 5 elements and print all 10 elements to the console.
- Write a program that calculates the sum of all elements in an array of 5 integers.
Lesson 7: Records
Objective: Introduce learners to records in Pascal, explaining how to declare and use them to store related data of different types.
Understanding Records:
A record is a data structure that can hold multiple values of different types. Records are useful when you want to group related data together, such as information about a person (name, age, and address).
Declaring a Record:
To declare a record, you define a new type with fields for each piece of data. Here’s an example:
type
TPerson = record
Name: String;
Age: Integer;
Address: String;
end;
In this example:
- TPerson: is the name of the record type.
- Name, Age, Address: are fields within the record, each holding different types of data.
Using Records:
Once you have declared a record type, you can create variables of that type and assign values to the fields:
var
person: TPerson;
begin
person.Name := 'Alice';
person.Age := 30;
person.Address := '123 Main St';
writeln('Name: ', person.Name);
writeln('Age: ', person.Age);
writeln('Address: ', person.Address);
end;
In this example:
- person: is a variable of type
TPerson
. - person.Name := 'Alice'; assigns the string 'Alice' to the
Name
field. - person.Age := 30; assigns the integer 30 to the
Age
field. - person.Address := '123 Main St'; assigns the string '123 Main St' to the
Address
field. - writeln('Name: ', person.Name); prints the value of the
Name
field to the console.
Exercises:
- Declare a record type to store information about a book (title, author, and year). Create a variable of this type, assign values to its fields, and print them to the console.
- Write a program that creates an array of records to store information about 3 different students (name, age, and grade). Print the information for all students.
Lesson 8: File Handling
Objective: Teach learners how to perform basic file operations in Pascal, such as reading from and writing to files.
Understanding File Handling:
File handling allows you to read from and write data to external files. This is useful for storing data persistently or processing large amounts of data.
Opening and Closing Files:
To work with files in Pascal, you need to open them first. You can open a file for reading, writing, or appending. Here’s an example of opening a file:
var
f: TextFile;
begin
AssignFile(f, 'data.txt');
Reset(f); // Open the file for reading
CloseFile(f); // Close the file when done
end;
In this example:
- AssignFile(f, 'data.txt'); associates the file variable
f
with the physical file 'data.txt'. - Reset(f); opens the file for reading.
- CloseFile(f); closes the file when the program is done with it.
Reading from a File:
You can read data from a file using the Readln
function. This reads a line of text from the file and stores it in a variable:
var
line: String;
begin
AssignFile(f, 'data.txt');
Reset(f);
while not Eof(f) do
begin
Readln(f, line);
writeln(line);
end;
CloseFile(f);
end;
In this example:
- Readln(f, line); reads a line of text from the file and stores it in the variable
line
. - while not Eof(f) do: loops through the file until the end of the file (EOF) is reached. The
Eof
function checks if the end of the file has been reached. - writeln(line); prints each line read from the file to the console.
- CloseFile(f); closes the file once all lines have been read.
Writing to a File:
Writing data to a file is similar to reading, but you use the Rewrite
or Append
functions to open the file, and Writeln
to write data:
var
f: TextFile;
begin
AssignFile(f, 'output.txt');
Rewrite(f); // Open the file for writing, erasing any existing content
Writeln(f, 'This is a line of text.');
Writeln(f, 'This is another line.');
CloseFile(f);
end;
In this example:
- Rewrite(f); opens the file for writing, clearing any existing content.
- Writeln(f, 'This is a line of text.'); writes a line of text to the file.
- CloseFile(f); closes the file after writing is complete.
Appending to a File:
To add new content to the end of an existing file without erasing its contents, you can use the Append
function:
var
f: TextFile;
begin
AssignFile(f, 'output.txt');
Append(f); // Open the file for appending
Writeln(f, 'This line is added to the existing content.');
CloseFile(f);
end;
In this example:
- Append(f); opens the file in append mode, allowing new data to be added to the end of the file.
- Writeln(f, 'This line is added to the existing content.'); writes a new line to the end of the file.
- CloseFile(f); closes the file after appending the new content.
Exercises:
- Create a program that reads all lines from a file named "input.txt" and prints them to the console.
- Write a program that creates a new file named "log.txt" and writes the current date and time to it. Each time the program is run, it should append the new date and time to the file.
Lesson 9: Subprograms and Modularity
Objective: Teach learners how to use procedures and functions to create modular, reusable code.
Understanding Subprograms:
Subprograms, which include procedures and functions, allow you to break down complex programs into smaller, manageable pieces. This makes your code easier to read, debug, and maintain.
Creating a Procedure:
A procedure is a block of code that performs a specific task but does not return a value. Procedures are useful when you need to execute the same code in multiple places within your program:
procedure Greet;
begin
writeln('Hello, World!');
end;
In this example:
- procedure Greet; declares a procedure named
Greet
. - writeln('Hello, World!'); is the code that will run whenever the procedure is called.
To call this procedure, simply use its name:
begin
Greet; // Calls the Greet procedure
end;
This will print "Hello, World!" to the console.
Creating a Function:
A function is similar to a procedure but returns a value. Functions are useful when you need to perform a calculation or operation that produces a result:
function Add(a, b: Integer): Integer;
begin
Add := a + b;
end;
In this example:
- function Add(a, b: Integer): Integer; declares a function named
Add
that takes two integer parameters and returns an integer value. - Add := a + b; calculates the sum of
a
andb
and returns the result.
To use this function and retrieve its result, you would call it like this:
var
sum: Integer;
begin
sum := Add(5, 10); // Calls the Add function and stores the result in sum
writeln('Sum: ', sum);
end;
This will print "Sum: 15" to the console.
Exercises:
- Create a procedure that takes a string parameter and prints a greeting message using that string. For example, if the parameter is "Alice," the output should be "Hello, Alice!"
- Write a function that calculates the square of an integer and returns the result. Test the function by calling it with different values and printing the results.
Answers to Exercises
Lesson 6:
Exercise 1: Declare an array of 10 integers. Assign values to the first 5 elements and print all 10 elements to the console.
var
numbers: array[1..10] of Integer;
i: Integer;
begin
for i := 1 to 5 do
numbers[i] := i * 10; // Assign values to the first 5 elements
for i := 1 to 10 do
writeln('Element ', i, ': ', numbers[i]);
end;
Exercise 2: Write a program that calculates the sum of all elements in an array of 5 integers.
var
numbers: array[1..5] of Integer;
i, sum: Integer;
begin
sum := 0;
for i := 1 to 5 do
begin
numbers[i] := i * 2; // Assign values to the array
sum := sum + numbers[i]; // Calculate the sum
end;
writeln('Sum of array elements: ', sum);
end;
Lesson 7:
Exercise 1: Declare a record type to store information about a book (title, author, and year). Create a variable of this type, assign values to its fields, and print them to the console.
type
TBook = record
Title: String;
Author: String;
Year: Integer;
end;
var
book: TBook;
begin
book.Title := 'Pascal Programming';
book.Author := 'John Doe';
book.Year := 2023;
writeln('Title: ', book.Title);
writeln('Author: ', book.Author);
writeln('Year: ', book.Year);
end;
Exercise 2: Write a program that creates an array of records to store information about 3 different students (name, age, and grade). Print the information for all students.
type
TStudent = record
Name: String;
Age: Integer;
Grade: String;
end;
var
students: array[1..3] of TStudent;
i: Integer;
begin
students[1].Name := 'Alice';
students[1].Age := 20;
students[1].Grade := 'A';
students[2].Name := 'Bob';
students[2].Age := 21;
students[2].Grade := 'B';
students[3].Name := 'Charlie';
students[3].Age := 22;
students[3].Grade := 'C';
for i := 1 to 3 do
begin
writeln('Student ', i, ':');
writeln(' Name: ', students[i].Name);
writeln(' Age: ', students[i].Age);
writeln(' Grade: ', students[i].Grade);
end;
end;
Lesson 8:
Exercise 1: Create a program that reads all lines from a file named "input.txt" and prints them to the console.
var
f: TextFile;
line: String;
begin
AssignFile(f, 'input.txt');
Reset(f);
while not Eof(f) do
begin
Readln(f, line);
writeln(line);
end;
CloseFile(f);
end;
Exercise 2: Write a program that creates a new file named "log.txt" and writes the current date and time to it. Each time the program is run, it should append the new date and time to the file.
var
f: TextFile;
begin
AssignFile(f, 'log.txt');
Append(f); // Open the file for appending
Writeln(f, 'Log entry: ', DateTimeToStr(Now));
CloseFile(f);
end;
Lesson 9:
Exercise 1: Create a procedure that takes a string parameter and prints a greeting message using that string. For example, if the parameter is "Alice," the output should be "Hello, Alice!"
procedure Greet(name: String);
begin
writeln('Hello, ', name, '!');
end;
begin
Greet('Alice');
end;
Exercise 2: Write a function that calculates the square of an integer and returns the result. Test the function by calling it with different values and printing the results.
function Square(x: Integer): Integer;
begin
Square := x * x;
end;
var
result: Integer;
begin
result := Square(5);
writeln('Square of 5 is: ', result);
result := Square(10);
writeln('Square of 10 is: ', result);
end;