Pascal Programming Exercises

For each program you should:

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.

Delphi pages Online tutorial Graphics
PP4S    

1: Read & Write Variables

  1. (Program, begin, end, writeln, readln, type char) Write a program which outputs one or more numbers and literal strings. Answer
     
  2. (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
     
  3. (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

  4. 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.
     
  5. (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
     
  6. (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

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

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

  1. (If) Rewrite Exercise 5 to allow a choice between left and right justification of the numbers. Answer

  2. 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.
     
  3. (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
     
  4. (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
     
  5. 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.

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

  1. (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
     
  2. (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
     
  3. (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)

  1. (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
     
  2. (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
     
  3. (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

  4. (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
     
  5. (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
     
  6. (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
     
  7. (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
     
  8. (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)

  9. (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...).

  10. (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.
     
  11. (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...?
     
  12. (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

  13. (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

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

  1. (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
     
  2. (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?
     
     
  3. (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

  1. (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

  2. (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

  3. 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.
     
  4. (function, gatherer) Write a program that calculates n! using a function. Answer
     
  5. (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.

  6. (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

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

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

  9. (for loop, stepper, gatherer) Writea program that calculates e from the formula 1 + 1 + 1/2! + 1/3! + 1/4!...

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

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

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

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

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

  4. (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.

  5. (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)
     
  6. 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 

  1. (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

  2. 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.
     
  3. (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
     
  4. (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
     
  5. (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

  6. 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.
     
  7. (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

  1. (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

  2. (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.
     
  3. (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
     
  4. (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.

  5. (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).

  6. Write a program that extracts the domain name from an email address. Answer. String functions explained.

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

  8. (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)
     
  9. (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
     
  10. (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)

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

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

  2. (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

  3. Write a program that takes two strings and outputs true if the second string s contained within the first.

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

  5. 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?

  6. 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
     
  7. Write a program that converts a decimal number into binary. Answer
     
  8. Write a program that converts a binary number into decimal. Answer
     
  9. Write a program that provides a choice between converting a decimal number into hexadecimal or a hexadecimal number into decimal.
     
  10. Write a program that takes two binary numbers and provides the option of either adding or multiplying them.
     
  11. 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.

  12. 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).

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

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

  15. Write a program that sets a string as a line of text and then searches for given substrings in the text.

  16. 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').

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

  18. Write a program that accepts a string of binary digits and verifies that the string consists of 0s and 1s.

  19. Write a program that converts a verified binary string into decimal. Extend the program to convert the binary string to hexadecimal.

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

  21. Write a program that creates a random password from a set of possible characters. Verify that the password meets criteria for a password.

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

  1. 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).

  2. 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).

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

  1. Graphics programming. Includes procedures.

13: Recursion

  1. (Recursion) Write a program which uses a recursive function to calculate n! What problems do you encounter when running the program? Answer
     
  2. (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

  1. (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.

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

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

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

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

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

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

  8. Extend the previous exercise so that words in the table with fewer than 5 letters are removed.

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

  1. (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
     
  2. (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
     
  3. (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
     
  4. 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
     
  5. 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

  6. (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

  1. (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

  1. (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 

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

  1. Rewrite the temperature conversion exercise (2.6) in OOP style.

  2. Rewrite the circle area and perimeter exercise (3.1) in OOP style.

  3. Rewrite the ISBN exercise (10.2) in OOP style.

  4. Rewrite the reverse string/palindrome exercise (10.1) in OOP style.

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