Explore procedures
To get started with structuring our code, let’s create a couple of useful procedures. We can build some small utilities that may be useful elsewhere, and create a test programs to explore how they work.
Print Line
Let’s start by creating a procedure to print a line of ’-’ characters to the Terminal. This could be useful when we create some terminal programs later, and we want to output something like a menu. The menu could have section separated by these lines.
How long should the line be?
Great question. We don’t have to have this set. Instead, we could add a length
parameter to allow the caller to say how long the line should be.
The following table provides an overview of the desired functionality of our print line procedure
Procedure | Print Line |
Parameters | length : The number of characters to print. Represents the length of the line. |
Description | Writes a number of ‘-’ characters to the Terminal. The number of characters to write is specified in the length parameter. |
The flowchart and pseudocode for this procedure are shown below.
Write Code and Test
We can code this up in a small test program. The following is a good start. The main function tests printing a few lines, and then gets the user to enter a length and uses that to print a final line. Have a go at this yourself, and refer to the code below if you get stuck.
Generalising Further
If we think about this, we could create a more general procedure that prints any character, or string, a number of times to the terminal. This could then be used to print repeated patterns or repeated text when needed, and we could use it to implement the print line procedure.
The following table provides an overview of a print repeated procedure. Have a go at implementing this, and using it to simplify the code in your print_line
procedure.
Procedure | Print Repeated |
Parameters | text : The text to repeat (a string). |
times : The number of times to print this. | |
with_newline : A boolean to indicate if a new line should be added to the end. | |
Description | Writes the text to the Terminal a given number of times, adding a new line when with_newline is true. |
Here is our updated test program - notice we want to keep print line, but you should be able to simplify it to a single line when you are done creating print repeated.
Test it out
See if you can create a print menu header. This could print a heading to the terminal in a box. For example, this could appear something like one of these options: