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
  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. (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
     
  5. (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
     
  6. (If) Rewrite Exercise 5 to allow a choice between left and right justification of the numbers. Answer
     
  7. (If, Repeat..until, and, most recent holder, transformation) Rewrite Exercise 2 so that only three-digit integers are accepted. Answer
     
  8. (If, Repeat..until, and, most recent holder, transformation) Rewrite Exercise 3 so that only values in the range -100 to +100 are accepted. Answer
     
  9. (If, odd, most recent holder, transformation) Rewrite Exercise 2 so that only even numbers are accepted for the number of decimal places to be displayed. Answer
     
  10. (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
     
  11. (If..then, transformation) Write a program which accepts a temperature value and then offers the user a choice between converting from C to F or from F to C. Answer
     
  12. (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
     
  13. (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
     
  14. (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. Answer
     
  15. (Repeat, stepper, gatherer) Write a program which accepts a sequence of numbers and calculates their sum and average. Ask the user to enter the number of values in the sequence. Answer
     
  16. (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
     
  17. (for loop, stepper) Write a program which outputs the first 10 triangle numbers: 1, 3, 6, 10, 15, etc. Answer
     
  18. (for loop, stepper, follower, initialisation) Write a program which outputs the Fibonacci sequence up to a user-supplied value and displays the 'golden ratio' each time. The output should be displayed as pairs of Fibonacci numbers followed by the golden ratio between them, eg f1, f2, f1/f2; f2, f3, f2/f3, etc. Answer
     
  19. (Nested for loop, stepper) 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
     
  20. (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.
     
  21. (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.
     
  22. (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.
     
  23. (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.
     
  24. (string, array, length, +, for) 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.
     
  25. (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.
     
  26. (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.
     
  27. (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.
     
  28. (Ord, chr, UpCase) 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. Can you think of a more effective algorithm for encrypting characters?
     
  29. (for loop) Write a program which displays the factors of a number (they do not have to be prime factors). Answer
     
  30. 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.
     
  31. (odd, mod) 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).
     
  32. 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. (PG)
     
  33. (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.) Answer
     
  34. 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
     
  35. (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
     
  36. (Repeat, nested loop, algorithm, tracing) Write a program which reads an integer and outputs its prime factors or declares that the number is prime. Answer
     
  37. (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.
     
  38. (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)
     
  39. 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)
     
  40. (function, gatherer) Write a program that calculates n! using a function.
     
  41. (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 polynomial function (n2) while the second is exponential (2n). Explain the difference between these functions.
     
  42. (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.
     
  43. (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.
     
  44. (Array, case, sorting, stepper) Write a program which inputs a sequence of numbers and outputs them in the same sequence, in reverse and in ascending order. Answer
     
  45. (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
     
  46. (ANSIstring, 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
     
  47. Write a program that converts a decimal number into binary.
     
  48. Write a program that converts a binary number into decimal.
     
  49. Write a program that provides a choice between converting a decimal number into hexadecimal or a hexadecimal number into decimal.
     
  50. Write a program that takes two binary numbers and provides the option of either adding or multiplying them.
     
  51. 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.
     
  52. Graphics programming. Includes procedures.
     
  53. 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).
     
  54. (Recursion) Write a program which uses a recursive function to calculate n! What problems do you encounter when running the program? Answer
     
  55. (function, while) Write a program which calculates the greatest common divisor of two integers or indicates that there are none other than 1. (PG)  Answer
     
  56. (Array of strings, sorting) Write a program which inputs a sequence of strings, stores them in an array and outputs them in order, in reverse and sorted into ascending alphabetical order.
     
  57. (String, function, val) Write a program which inputs a real number as a string and converts it to numeric format. (PG)
     
  58. (function, val) Write a program which inputs an integer as a string and converts it to a number - do not use 'val' until you have written your own function! Answer
     
  59. (Mod, div, String, function, str) Write a program which inputs an integer and converts it to a string - do not use 'str' until you have written your own function! (To do this read the numbers as characters from the input stream and obtain their numeric value from their position in the ANSI character set - numeric_value = radix * numeric_value + ord (ch) - ord ('0')). Answer
     
  60. (String, function, str) Write a program which inputs a real number and converts it to a string.
     
  61. (2d arrays) Write a program which creates a 12x12 product table. Prompt the user for 2 numbers in the range 1-12 and display their product, which should be looked up from the table using the input values as indices.
     
  62. (Text files, assign, reset, rewrite, close, Eof) 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.
     
  63. (record, procedure) Write a program which defines a record for pupils with fields for name, form and year of entry. The data entry and display should take place in separate procedures. Answer
     
  64. (Array of records) Extend the previous exercise to provide entry of data to an array of pupil records. Add procedures to sort the records alphabetically by name and by form. All options in the program should be listed in a menu. Answer
     
  65. (Case and menu) 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. Sort the pupils by exam score and output them. Answer
     
  66. (Typed files) Extend the Pupil and Form lists exercise with file routines. This will involve three changes : the declarations, the file routines and extensions to the menu. Answer
     
  67. 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
     
  68. 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
     
  69. Write a program which takes the scores on two examination papers for pupils doing a range of subjects, maximum three. Calculate the total mark and grade achieved in each subject. Provide a suitable file structure for storage on disc. Provide a sort routine for ranking the scores within each subject and output the results. Provide the means also to output the data as an alphabetical list with each subject listed for each pupil.
     
  70. (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 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.
     
  71. (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
     
  72. 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;

Back to Pascal Home Page