Pascal Programming Exercises
For each program you should:
- try to figure out what is required;
- if you can't write the code from existing knowledge look at the answer and try to understand that;
- go back to the compiler and try to write the code again without looking at the answer;
- keep trying to write the code until you succeed;
- pay particular attention to the
variable types used in the
program; the links are to definitions which are part of the specification.
It may seem hard at first but practice is the main thing that is required so that the keywords and the syntax become more familiar and ingrained into your mind. We will go through
many of the exercises during the course. Don't panic at this stage if you find
it hard to get started; it takes time to absorb everything that you need to know and it may take you a while to pick up.
1: Read & Write Variables
- (Program, begin, end, writeln, readln, type char) Write a program which outputs one or more numbers
and literal strings. Answer
- (Type integer, arithmetic operators, integer operators) Write a program
which reads two integers and then displays a) their product and b) their
quotient when the first is divided by the second. Answer
- (Type real, format descriptor) Write a program which accepts three real
numbers, computes their sum and outputs the result. Amend the program so
that the result is output to 2 dp. Answer
- Write a program that takes in the width, length and height of a room in metres and returns the volume of the room in cubic metres. Give the answer in centimetres as well. Choose integer or real as you think fit.
- (Format descriptor) Write a program which accepts two real numbers, a
value for the number of decimal places, calculates the sum and outputs the
result. Try entering a real number for the number of decimal places.
Answer
- (Format descriptor) Write a program which accepts a sequence of real
numbers and then outputs them in the following formats: a) decimal points
in line; b) left justified; c) right justified. (Two of these are the same -
can you see which ones?) Answer
- Write a program which takes an amount of money in £ and then gives the minimum number of notes or coins that could make up this number e.g. £34 = 1x£20, 1x£10, 4x£1. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code.
- Write a program which finds the roots of a quadratic equation from the three
coefficients (a, b, c) using the formula roots= (-b +- sqrt(b ^2 -4ac)) /
2a. (a is the coefficient for x2 b for x and c for the numeric
part.) (PG) Answer
2: Selection with If
- (If) Rewrite Exercise 5 to allow a choice between left and right
justification of the numbers. Answer
- Write a program that takes a temperature for water in either degrees F or C and outputs whether the water is freezing or boiling or neither.
- (If..then, transformation) Write a program which accepts a temperature value for water and then
offers the user a choice between converting from C to F or from F to C. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code. Answer
- (Pre-defined functions, round, trunc, typecast, if..then, type char, transformation) Write a
program which accepts two real numbers, asks whether the user requires a
rounded or truncated result and then outputs their product in the form
requested. Answer
- Write a program that accepts input for number of hours worked in a week and hourly rate of pay. Hours worked over 40 should be paid at 1.5 times the base rate.
- Write a program that accepts a mark for an exam out of 60, converts it to a percentage and outputs a grade based on the score. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code.
3: Constants
- (Constants, fixed value, transformation) Write a program which takes the radius of a circle as
input and returns its area and circumference (pi = 3.14159).
Answer
- (Constants, fixed value, transformation) Write a program which sets up a constant for base rate tax,
inputs the gross pay and returns the net pay.
Answer
- (Constants, fixed value) Write a program which sets up constants for base rate and
higher rate tax (try 20% and 40%) and the tax thresholds for basic and
higher rates (try £5,000 and £30,000). After inputting the gross pay the
program should return the net pay according to the thresholds and rates.
Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code.
Answer
4: Loops (For, Repeat, While)
- (If, Repeat..until, and, most recent holder, transformation) Rewrite Exercise 1.2 so that only three-digit integers are
accepted. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code. Answer
- (If, Repeat..until, and, most recent holder, transformation) Rewrite Exercise 1.3 so that only values in the range -100 to +100 are
accepted. Answer
- (If, odd, Repeat..until, most recent holder, transformation) Rewrite Exercise 1.3 so that only even numbers are accepted for
the number of decimal places to be displayed. Answer
- (Repeat, stepper, gatherer) Write a program which accepts a sequence of numbers and calculates
their sum and mean average. Ask the user to enter the number of values in the sequence.
Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code.
Answer
- (for loop, stepper,
most recent holder) Write a program which outputs the multiplication table of the
user's choice. Each line should read, for example, "3 x 13 = 39",
where 13 was the number entered by the user.
Answer
- (for loop, stepper, most recent holder) Write a program which outputs the first 10 triangle numbers: 1, 3, 6, 10, 15, etc.
Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code.
Answer
- (Nested for loop, stepper,most recent holder) Write a program which takes two integer values from
the user and outputs the multiplication tables between the first and second
numbers. (e.g. 4 and 7 will output the 4 times table, the 5 times table, the 6
times table and the 7 times table). Answer
- (for loop, stepper, gatherer) Write a program which sums the terms of the harmonic series
(1 + 1/2 + 1/3 + 1/4...) up to a limit supplied by the user. Output the
values as floating point and as a fraction.(PG)
- (for loop, stepper, gatherer) Write a program that uses the following formula to calculate pi: pi=4(1 - 1/3 + 1/5 - 1/7 + 1/9...).
- (For, downto, run time errors,
try-except,
stepper)
Write a program which divides a number by a
successively smaller number of values. Try to extend the range of values
from, say, 5 to -5 and observe the result.
Provide a suitable error trapping routine to prevent this error from
happening. Answer.
- (if..then..else) Write a program which outputs part of a sequence of
numbers on the screen and then invites the user to enter the next number
(e.g. 2,4,6,8,? answer 10 - this is an easy example). The formula for finding
the next number will be in the for loop e.g. next := next * 3. Display messages according to the success achieved. A
BIO question asked for the next number in the sequence 1 2 4 8 16 23 28 38
49. This is tricky to spot and trickier to code than 1, 4, 9, 16, 25, 36,
etc. And how about this one: 1; 11; 21; 1211; 111221; 312211...?
- (Nested for loop)
Write a program which finds and displays the 'perfect numbers' up to a
user-supplied value. (A perfect number is one whose factors add up to the
number itself, eg 6 = 1+2+3.) Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code. Answer
- (single, double, extended) Write a program that calculates the frequency of notes on
a piano. The ratio of two musical notes a semitone apart is the 12th root of 2
(take the square root of 2 twelve times - keep pressing the calculator
button until 1.059463094). Middle A is 44 cycles per second, the lowest note
is 4 octaves below this. There are 88 notes on a concert piano. (PG)
Answer
- Write a program that examines a set of integers (including negative
ones) and determines whether there is a sub-set of the
numbers that sums to zero e.g. {−7, −3, −2, 5, 8} Look here.
5: Pre-defined Functions
- (Ord, chr, ANSI) Write a program which uses two methods to print the ANSI sequence from 'space' (chr(32) or ' ') to 'z' (chr(122)), one using ord and the other using chr.
Answer
- (Ord, chr, length(), UpCase, string) Write a program that takes a string such as a name and encrypts it by finding the numerical value of each character and adding 1 to this (or any other value). The code should convert the altered numeric value to the corresponding character and build a copy of the encrypted string. Extension: convert the encrypted characters to upper case. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code. Can you think of a more effective algorithm for encrypting characters?
- (odd, mod, loop) Write a program that takes a single input value and then applies these
rules until the answer is 1: if the number is even divide by 2; if the
number is odd multiply by 3 and add 1. Output the numbers produced. Is there
a pattern in the output? Will all input numbers eventually reach 1? (The odd function takes the form odd(n) and returns a Boolean; so if n=1 or 3 or 5 etc. then odd(n) returns true while if n=2 or 4 or 6 etc then odd(n) returns false).
6: User-Defined Functions
- (Case, function) Write a program which takes two values from the user and then
offers a choice between the four basic arithmetic operations to be
performed. Use a menu, case and a function for each operation.
Answer
- (function, for loop, stepper,
follower, initialisation) Write a program which
includes one function to calculate a Fibonacci number from the previous two
numbers and another function to calculate the golden ratio from two
Fibonacci numbers. The program should take a
user-supplied value and display the Fibonacci sequence up to that value,
along with the golden ratio for the current value divided by the previous
one. Answer
- Write a program that includes a function to calculate the greatest
common divisor of two numbers. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code.
- (function, gatherer)
Write a program that calculates n!
using a function. Answer
- (function) Write a program that includes a function to calculate m
to the power n. Use this function to illustrate the difference between n to
the power 2, 3, etc. and 2 to the power n, where n is 2, 3, 4, etc. The
first of these is a quadratic function (n2) while the second is
exponential (2n). Explain the difference between these functions. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code.
- (for loop) Write a program which displays the factors of a number (they do not have
to be prime factors). Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code. Answer
- (Repeat, function, nested loop, algorithm, tracing) Write a program which reads an integer
and outputs its prime factors or declares that the number is prime. Make sure the prime factor routine is in a function. Write the algorithm for this in pseudo-code and/or flowchart format before proceeding to the code. Answer
- Write a program which converts between currencies. You could do this by asking the user for the two currencies, the amount and the exchange rate or you could store a range of currency exchange rates in an array or in a file that is read into an array at run-time. This would work well in a GUI program.
- (for loop, stepper, gatherer) Writea program that calculates e from the formula 1 + 1 + 1/2! + 1/3! + 1/4!...
- Write a program that takes the product of two prime numbers and then
finds its factors. e.g. enter 77: factors are 7 and 11. Answer
- Write a program that takes a number and finds the powers of 2 that sum to that number e.g. 25 = 1 + 8 + 16. Answer
7: Procedures
- Write a program that defines a procedure with two input parameters, one an integer, n, and the other a character, c. The procedure will output the character n times.
- Write a program that defines a procedure that takes two input parameters and returns them in ascending order, either numeric or dictionary, according to whether you choose numeric or string variables.
- Write a program that includes a procedure that takes an odd number as a parameter and prints an upside down triangle of stars that starts with the input value and decreases by 2 until the last row contains a single character.
- (Boolean, string, if, procedures) Write a program which takes a date as three numbers and
returns output in the form number/string/number eg 12th November 1992. Include error
checking on the range of acceptable numbers for the day and month, and check
that the numbers entered for the day are valid for the month (eg 30/2/99, or
31/6/02). Use an appropriate technique to explain the action of the program.
Dry run the program with these dates: 1/4/76, 29/2/2008, 31/12/2005 and show
what happens. Write out a test plan of 10 dates for testing the program,
showing that it can handle both valid and invalid dates. Rewrite the code
using procedures for reading the three values, finding the suffix for the
day and finding the name of the month. Answer.
- (procedure) Write a program which takes a rational number from the user as a numerator and
a denominator. Write a procedure which removes common factors from this number,
eg 15/24 = 5/8. To do this you will have to find the gcd of the two numbers and
then divide the original values by this eg gcd of 15 & 24 is 3, 15/3=5,
24/3=8. (PG)
- Extend the previous exercise to include a procedure to add two rational
numbers, eg 2/7+1/6=12/42+7/42=19/42. Finally, use the procedures you now have
to find partial sums of the harmonic series. For 1/1+1/2+1/3 we have:
6/6+3/6+2/6=11/6. Adding 1/4 we have 11/6+1/4=23/12+3/12=25/12, etc.
(PG)
8: Arrays
- (Array) Write a program which fills an array with
a sequence of numbers such as a multiplication table. The user should then
be able to specify a value from the table by its index value. For example,
if the table contains 5, 10, 15...50, the user should be able to input 6 and
obtain the result 30 from the table (6x5). Extend this to a 12 x 12 table so the user can specify two values and retrieve the product.
Answer
- Take the Fibonacci program that you wrote earlier and store the Fibonacci numbers in a table so that a user could specify the nth Fibonacci value and the program
will then look it up in the table. Extend this to store the golden section values as well.
- (Array, linear search, stepper,
most
wanted holder). Write a program that populates a list with a range of
values and then finds the largest and smallest values in the list.
Answer
- (Array, case, sorting, stepper)
Write a program which inputs some strings (such as
names) and outputs them in
the same sequence, in reverse and in ascending order. Use a menu to allow
the user to choose the option required. Answer and
Sorting methods
- (Array, concatenation) Write a program which accepts an integer from the user and
outputs the equivalent in Roman numerals. Your program should allow input of
numbers up to 3,999. Answer
- Write a program that plays noughts and crosses with the user. The
program should allow the user to choose who goes first and then play a game
with the user. The program should check after each turn whether there is a
winning position. The program should indicate the winner and whether a game
was drawn.
- (function)
Write a program that calculates the values of m ^ n mod p for n = 1, 2, 4, 8, 16... Store the results in an array.
e.g. 18 ^ 1 mod 55, 18^2 mod 55, 18^4 mod 55, 18^8 mod 55. Hence, using the
previous program about sums of powers of 2, find a way to calculate e.g. 18^7 mod 55, which is 18^1
mod 55 x 18^2 mod 55 x 18^4 mod 55.
9: String Functions
- (UpCase, function) Write a program which accepts a string
and converts it from upper to lower case or from lower to upper case.
String functions explained.
Answer
- (string, concat(), +) Write a program that reads a
first name and a second name from the user and joins them together in a
single string (concatenation).
String functions explained.
- (string, array, length, pos) Write a
program that takes first name and second name as a single string from the
user and separates them into two substrings.
String functions explained.
Answer
- (string, length, for) Write a
program that takes a last name and an 8 digit ID code and creates a login ID
from the first four letters of the name and the last four digits of the ID.
String functions explained.
- (string, function) Write a program that reads a
string and validates the characters in it,
which should be a..z, A..Z, 0..9, _, - and . (the characters of an email or
web address).
- Write a program that extracts the domain name from an email address.
Answer.
String functions explained.
- (string, pos, copy) Write a program that validates
an email address by searching for the @ character and checking that the name and server parts are valid.
Answer.
String functions explained.
- (String, function, val) Write a program which inputs an integer as a string and converts it to numeric format
(do not use strtoint: write your own function). (PG)
- (function, val) Write a program which inputs an integer and
converts it to a string - do not use 'val' or 'inttostr' until you have written your own
function! Answer
- (String, function, str) Write a program which inputs a real
number and converts it to a string (do not use floattostr until you have
written your own function)
- Write a program that reads a string in upper case and converts it to lower case (no pre-defined function for this: you will have to use ord() and chr().
10: Strings
- Write a program that takes a string from the user (a line of text), takes a single character and then outputs the position of each occurrence of the character in the string. Define a suitable action and output if the character is not in the string.
- (String, function) Write a program which inputs a string (such as a name)
and outputs it in normal and reverse. Add a routine to test whether the
string is a palindrome ('madam', etc.) Answer
- Write a program that takes two strings and outputs true if the second string s contained within the first.
- Write a program that inputs a string of words, a word that might be in the string and outputs the number of times that the given word occurs in the string.
- Write a program that takes two strings and outputs the number of times that each character appears in both of them and a string of the characters found. How many times does your code process a character?
- Write a program that inputs 9 digits of an ISBN code and calculates the check digit.
This is a good point at which to include a try..except structure to check that each character entered is a digit. Answer
- Write a program that converts a decimal number into binary.
Answer
- Write a program that converts a binary number into decimal.
Answer
- Write a program that provides a choice between converting a decimal number into hexadecimal
or a hexadecimal number into decimal.
- Write a program that takes two binary numbers and
provides the option of either adding or multiplying them.
- Write a program that takes a binary number and
provides the option of either inverting it (one's complement) or converting
it to two's complement.
- Write a program that reads two 8 bit binary strings and offers the
choice of OR, AND and XOR operations on them (compare the strings bit by bit).
- Write a program that reads 7 bit binary codes and adds a parity bit to bit 7, thus making them 8 bits long. Use even parity.
- Write a program that reads strings of 12 bits and sets check bits according to the Hamming code (in positions 1, 2, 4, 8 where 1 is the left-most bit). Use even parity. The program should display the data with the Hamming codes set and it should then allow the user to specify a change of one or more bits and report on where the error/s occurred.
- Write a program that sets a string as a line of text and then searches for given substrings in the text.
- Write a program that encrypts a string using a Caesar shift. Extend the
program so that it will decrypt text using the same key. Extend the program further by allowing the user to calculate the shift from a multiplication as well as an addition (e.g. multiply 'A' by 2 gives 2x65=130; 130+ e.g. 1 = 131; 131 mod 64 = 67='C').
- Write a program that encrypts a string using a substitution cipher.
Extend the program so that it will decrypt text using a reasonable
substitution strategy to replace letters and hence present an understandable
message.
- Write a program that accepts a string of binary digits and verifies that
the string consists of 0s and 1s.
- Write a program that converts a verified binary string into decimal.
Extend the program to convert the binary string to hexadecimal.
- Write a program that accepts user input of a password according to the following rules:
between 6 and 10 characters in length;
contains at least one upper case character (A-Z);
contains at least one lower case character (a-z);
contains at least one numeric character (0-9);
contains at least one of (! @ $ % & * ( ) - _ = + [ ] ; : , < . > / ? );
spaces are not allowed;
must not begin with ! or ?
repeating characters are not allowed e.g. EE, 66.
1 mark each up to 8.
- Write a program that creates a random password from a set of possible characters. Verify that the password meets criteria for a password.
- Write a program that recognises <p> and </p> tags in a piece of HTML and displays the text in between, including any use of the < and > characters. Extend the code to accept a range of HTML tags such as <h?></h?>, <table>, <tr>, td>, <ol>, <ul>, <li> and so on.
11: Grid Problems
- Write a program that allows the user to write in 9 digits that will
populate a 3 x 3 2-D array in random positions.
Have the program check that the grid contains 1 each of the nine digits (as
in Sudoku).
- Write a program that finds all the solutions for a 3x3 magic square
using numbers 1-9. The central value is always 5 but the remaining 8 may be
any value (unless you also take account of the fact that the odd and even
numbers always fall in the same cells).
- Write a program that adds single random letters to the cells of a
2-dimensional array (say, 10 x 10). Display the array of characters. Extend
the program to add a word at a location in the array chosen by the user. The
user should be able to specify the starting cell by a pair of values to
represent the x-y address of the cell. The user should also be able to
specify whether the word runs horizontally or vertically from the given
point. The program should then discover the word in the array for itself (as
in a word puzzle when you have to find words in a grid of random letters).
The program needs to know what word it is looking for. Extend the program
further by allowing for diagonal placement of a word, to the left or right.
Finally, extend the program so that it reads up to 5 words and searches for
all of them.
12: Graphics
- Graphics programming.
Includes procedures.
13: Recursion
- (Recursion) Write a program which uses a recursive
function to calculate n! What problems do you encounter when running the
program? Answer
- (Recursion) Write a program that defines a recursive function to find a given Fibonacci number (Fibonacci number 5 is 3, number 6 is 5, number 7 is 8, etc.)
Answer
14: Text Files
- (Text files, assign, reset, rewrite, close, Eof, printing)
Write a
program with a menu which offers the following choices to the user : Input
of text from the keyboard until a special character is pressed (eg '@');
Output of text from a file; Quit. Answer. Extend the code to include a way of storing file names in a separate file. Extend it again to include a routine to print the contents of a file.
- Write a program that reads a file of comma separated binary digits and stores them as 8 bit strings. Convert each 8 bit string into its ASCII character and display the characters as a message. Think carefully about what data structure you could use to store the bytes of data and the characters they represent. When the message has been read the program should store the message in a text file. Answer
- Write a program that takes a simple text message in a text file and converts it into a CSV file of bits derived from the ASCII values of each letter.
- Write a program that reads a record structure from a CSV text file consisting of Name, Date of Birth (in dd/mm/yy format) and House. The records are stored one per line in the CSV file. The program should skip over the comma separators and read the fields into their respective holders. Write additional routines to sort the data by age (oldest first) and to accept new entries for the file. Display the sorted list with the names arranged as Surname, First Name, Date of Birth.
- Write a program that will read a HTML file and output the text elements as a text stream. This should include attributes such as the 'alt' part of an <img> tag and also typographical information such as headings, lists and block quotes. This would probably work better in a GUI environment where you would have more control over the display.
- Write a program that reads a piece of text from a file and matches all words in the file that meet a certain pattern such as 'br*v*'. Draw the state table and the finite state machine for this problem before you code it.
- Write a program that reads a text file and identifies the words in each line. Each word should be added to a table and a count of each word displayed alongside it.
- Extend the previous exercise so that words in the table with fewer than 5 letters are removed.
- Extend the previous exercise so that the words in the table (of 5 letters or more) are replaced in the text with suitable labels so that the text is compressed. Compare the size of the new and the original text files.
15: Typed Files: Sequential
- (Typed files, record, procedure, printing) Write a program which defines a record for pupils with
fields for last name, first name, form and year of entry. Use a menu and
procedures. Make sure the data can be output to a printer.
Answer
- (Typed files, array of records, printing) Extend the previous exercise to provide entry of data to
an array of pupil records. Add procedures to sort the records alphabetically
by name or by form. All
options in the program should be listed in a menu.
Make sure the data can be output to a printer. Answer
- (Typed files, printing) Extend the Pupil and Form lists exercise by
adding file
handling routines. This will involve three changes : the declarations, the file
routines and extensions to the menu. Make sure the data can be output to a printer.
Answer
- Add a routine to the pupil program to allow searching of the list of names
for one specified by the user. If the name is not present a suitable message
should be output. Answer
- Add procedures to the pupil program to allow amendments to be made to the
files. These should include new records, deleting records and changing field
data in records. Answer
- (Typed files, case and menu, printing) Write a program which takes the name, form and two
examination marks for pupils. Add the marks for each pupil and calculate the
total and grade for each one. Allow sorting by either exam score or name.
Add routines to store the data in a file and retrieve them later. Make sure the data can be output to a printer.
Answer
16: Typed Files: Direct Access
- (Hash functions) Amend the Pupil and Form exercise so that records are positioned in the
file according to a hash function based on the letters in the surname. You
should then be able to store new names and retrieve existing ones from the
surname alone. You will need to leave the files around half empty and check for the status of a location (empty or
occupied) and you will also need to be able to search sequentially for an
empty location if the target is occupied. The data will no longer be in
order on the disc so you will have to devise a different way of displaying
sorted listed.
17: Units
- (units). Rewrite an exercise such as 37 (Roman Numerals) with the
declarations, functions and procedures moved to a unit, leaving only the
main program section. Answer
18: General Problems
- Write a program that simulates a supermarket till. On reading a code for
an item sold the program should: look up the code in a file and find the
item name and the price; add the name and price to a till receipt; keep a
running total of the value of goods purchased; deduct one from a master file
of items in stock; take account of special deals such as BOGOF (how might
such information be made available to the program?); calculate the total
value of the items purchased; subtract any savings from the total; print the
till receipt;
19: OOP
- Rewrite the temperature conversion exercise (2.6) in OOP style.
- Rewrite the circle area and perimeter exercise (3.1) in OOP style.
- Rewrite the ISBN exercise (10.2) in OOP style.
- Rewrite the reverse string/palindrome exercise (10.1) in OOP style.
- Write a program in OOP style that sets up a base class 'employee' with properties and methods for calculating pay and tax. Set up two sub-classes to store information on employees who are paid by monthly salary on the one hand and hours per week on the other. The amount of tax paid should be based on approximate national rates: the first £8000 is tax free, the next £30000 is at 20% and earning over £38,000 are taxed at 40%.
Back to Pascal Home Page