0% found this document useful (0 votes)
6 views

2.3.1 - 2.3.6 Programming Basics, Selection, Built-In Functions & Structured Programming 2

Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

2.3.1 - 2.3.6 Programming Basics, Selection, Built-In Functions & Structured Programming 2

Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Programming Basics, Selection, Built-in

Functions & Structured Programming


2.3.1 – 2.3.6
Programming

What are good program writing techniques?


Programmers should write code that is self-documenting and split into small sections.
Specifically, the programmers should:
 use meaningful identifier names for variables, constants and subroutines;
 use declared constants;
 annotate code with comments;
 indent code within iteration and selection;
 split the code into modules when possible;
Programming
The need for good program-writing techniques
It is important for a programmer to use good programming techniques when writing code so that the code:

 can be easier to understand by other programmers (who are either part of the programming team, or who will be

responsible for the maintenance of the program in the future);

 can be understandable by the programmer himself in the future;

 is split into smaller blocks which are easier to debug individually and update;

 is less prone to errors – because the meaningful variable names and comments make it self documenting and

easier to read.
Programming
Variable
 A variable is a value that can change during the execution of a program.
Constant
 A constant is a value that is set when the program initializes and does not change during the program’s execution.
Identifier
 Identifier is the name given to a variable, constant or subroutine.
 Assigning a variable or constant an identifier name means that it can be easily referenced from any part of the
program within its scope and it helps to make the program more readable.
Reserved word/keyword
 Reserved words (occasionally called keywords) are one type of grammatical construct in programming languages.
These words have special meaning within the language and are predefined in the language’s formal specifications.
Programming
Declaration
 A declaration is a statement in a program that gives the compiler or the interpreter information about a variable or
constant that is to be used within a program.
 A declaration ensures that sufficient memory is reserved in which to store the values and also states the variables’
data type. Reserved words/keywords cannot be used as identifier names as this generates a compiler error and
comes under the category of syntax error.

Declaration of local variables


 DIM MyCounter AS Integer
 DIM FirstName, LastName AS String ‘declares two variables
 DIM TheLength AS Single
 DIM DOB AS Date
 DIM OverDueFlag AS Boolean
Programming
Intrinsic variable declarations
 Some programming languages require intrinsic variable declarations. This means that variables must be declared
before they are used. The advantage of intrinsic variable declaration is that it cuts out possible errors due to the
misspelling of a variable name – if a variable is used that has not been declared, the programming translator will
identify it as an error.
DIM Number As Integer
Number= Nubmer+1 ‘This will be flagged as an Error!
 There are two types of variables used by programmers and they are categorized according to their scope.
Programming
Scope
 Scope indicates whether a variable can be used by all parts of a program or only within limited sections of the program –
for example, within a subroutine.
Global variable
 A global variable is one that is declared at the start of the main program and is visible (useable) everywhere in the
program and exists for the lifetime of the program.
 Note that if one procedure changes the value of a global variable, then the next procedure that uses the variable will be
given this changed value – this is a common cause of errors.
Local variable
 A local variable is one that is only visible inside the procedure or function in which it is declared.
 Note that a local variable cannot be referenced from outside the procedure. In fact a local variable does not exist until the
procedure starts executing and it disappears when the procedure stops executing.
 Thus any value that is held by a local variable is only stored temporarily.
 The lifetime of a local variable is the lifetime of the procedure in which the local variable is declared.
 The advantage of using local variables rather than global variables is that the same variable names can be used in several
Programming
Using declared constants
 Constants will be declared at the start of the main program. The following shows the declaration of constants for
Pi and the VAT rate
 CONST Pi = 3.142
 CONST VatRate = 0.175
Declaring constants at the start of a program means that maintenance is made easier for two reasons:
 If the value of a constant changes, it only has to be changed in the one part of the program where it has been
declared, rather than in each part of the program in which it is used;
 the code is easier to interpret:
Total=VatRate*CostPrice ‘allows a greater understanding rather than
Total=0.175*CostPrice
Assignment
 An assignment is an instruction in a program that places a value into a specified variable.
 Some typical assignments are:
TheLength = 20.5
TheUsersName$ = “Charlie”
TheArea = TheWidth * TheLength
TotalCost = LabelledCost + 15
Counter = Counter + 1
 Note that the last example is a common method used to increment the value of a variable. It could be read as:
“The new value of Counter is its existing value plus one”
Programming
Type Mismatch errors
 A type Mismatch error occurs in a program when a variable has been declared as one data type, but it is later
assigned a value that is of an incompatible data type.
 The following code will produce a ‘Type Mismatch’ error because “Charlie” is not an integer:
DIM MyCounter AS Integer
MyCounter = “Charlie”
Other Type Mismatches will be produced by the following:
DIM RentalDateAs Date
MemberRentalDate = “September”
DIM ShoeSizeAs Integer
JohnsShoeSize = 10.3
 Note that a variable that is declared as a string will never produce a type mismatch error.
Programming
Arithmetic Operator

Powers
Programming
Division
A result of a division such as 17 ÷ 4 can be expressed either as a real (4.25) or as two integers (4 remainder 1).
The integer method, in most programming languages, uses the operators DIV and MOD.
Programming
Relational operators (=, <, <=, >, >= and <>)
Relational operators are used in the format: [Expression] [Operator] [Expression] and will always return a Boolean
(True or False) value.
Relational operators are typically used with the “IF” selection and also within conditional loops (REPEAT-UNTIL or
WHILE-WEND).
In the following table, the variables “a” and “name$” have the following assignments:
a=3+5
name$=“JAMES”
Programming
In the following table, the variables “a” and “name$” have the following assignments:
a=3+5
name$=“JAMES”
Programming
Boolean operators AND, OR and NOT
AND and OR
The AND & OR operators always return a Boolean result and are used in the format:
[Boolean] [Operator] [Boolean]
The following ‘truth’ table summarizes the result of the Boolean operations:
Values Results
Programming
NOT
The NOT operator reverses the result of the Boolean expression and is used in the format:
NOT [Boolean]
The following truth table summarizes the NOT operation:
Programming
Examples of Boolean ‘logic’
Consider the following algorithm, which is used to monitor a printer and display its output via a LCD display in the front panel:
IF NOT(PaperTrayEmpty) AND (FilesWaiting> 0) THEN
OUTPUT “PRINTING…”
ELSE
OUTPUT “PLEASE ADD PAPER”
END IF
If the values of the variables are:
PaperTrayEmpty = False
FilesWaiting = 2
Then the output will be “PRINTING…”
The following table shows why:
Programming

in whichPaperTrayEmpty = False.
To avoid this incorrect message, the algorithm should be rewritten using a nested IF, as shown on the next page:
IF PaperTrayEmpty THEN
OUTPUT “PLEASE ADD PAPER”
ELSE
IF FilesWaiting> 0 THEN
OUTPUT “PRINTING…”
ELSE
OUTPUT “STATUS OK”
END IF
Programming
Meaningful identifier names
Identifiers are used to give names to constants and variables. They are also used to name procedures, functions, and
the main program.
Naming conventions
Most of the identifier names must conform to the following rules (different programming languages may have
slightly different rules):
1. they must be unique;
2. spaces must not be used;
3. they must begin with a letter of the alphabet;
4. the rest of the identifier must not contain punctuation – it may only consist of a mixture of letters and
5. digits (A–Z, a–z and 0–9) and the underscore character ‘_’;
6. they must not be a ‘reserved’ word – eg Print, Repeat, For, Dim, Loop, etc.
Programming
Recommended naming policies
Do not use spaces within identifier names – even with programming languages where they are permitted. Instead,
use the underscore character ‘_’ or, better yet, type names in lowercase except the first letter of each word, which
should be typed in uppercase.
Examples of good identifier names:
FirstName LastName PostCode TelephoneNumber WeightAtBirth TestScore AverageHeight
Further clarity can be given to identifier names by including a prefix that identifies the data type. The above
identifiers would be clearer if given the following prefix data types:
strFirstName strLastName strPostCode strTelephoneNumber sglWeightAtBirth
intTestScore sglAverageHeight

Initializing a variable means setting it to a starter value. Initialization will usually set the value of an integer to 0 or 1
and a string to Empty (“”).
Programming
The following code initializes the variable Counter to zero before it is used in the iteration:
Counter=0 (the variable is initialized)
REPEAT
Counter=Counter+1


UNTIL Counter=10
Initializing a variable ensures that its value has not be been retained from a previous use of the routine and that the
value has not been accidently set in another part of the program – this helps avoid errors.
Programming
Comments/remarks
Comments (originally called remarks) are added to program code to provide useful, or essential, documentation for
the programmer and other people who read the code. All programs/subroutines should contain comments to indicate:
 the details of the person who wrote the code;
 the date that the code was written;
 the purpose of the code;
 how parts of the code work;
 the use of certain variables.

Comments can be used anywhere in a program – either as separate lines by themselves or on the same line as
executable code provided they appear to the right of any code that will execute.
Comments are usually indicated by the use of an apostrophe (‘), or two forward slashes (//).
Programming
Indentation should be used within iteration and selection statements so that it is clear which instructions go together.
Original code Indented code

INPUT Number INPUT Number


Total=0 Total=0
WHILE Number > 0 THEN WHILE Number > 0 THEN
Left=Number MOD 10 Left=Number MOD 10
Right = Number DIV 10 Right = Number DIV 10
Total=Total+Left Total=Total+Left
Number=Right Number=Right
END WHILE END WHILE

Original code Indented code

FUNCTION TEST(X) FUNCTION TEST(X)


IF X=1 THEN IF X=1 THEN
PRINT 1 PRINT 1
RETURN 1 RETURN 1
ELSE ELSE
Number=X*Test(X-1) Number=X*Test(X-1)
PRINT Number PRINT Number
RETURN Number RETURN Number
END IF END IF
END TEST END TEST
Selection
Selection is a control structure in which there is a test to decide if certain instructions are executed.
IF-THEN-ELSE
This selection method is used if there are two possible outcomes to a test:
IF x < 0 THEN
OUTPUT “Sorry, you can’t have negative values”
ELSE
a = x*x
OUTPUT a
END IF
Selection
Selection
SELECT-CASE
This selection method is used if there are more than two possible outcomes to a test:
SELECT CASE KeyPress
CASE LeftArrow
Move one character backwards
CASE RightArrow
Move one character forwards
CASE UpArrow
Move one character up
CASE DownArrow
Move one character down
END SELECT
Selection
Built-In Functions
Location
Many programming languages allow the searching for a short string of characters within a longer string. This would
be similar to searching this book for the word ‘computer’.
Common Key words for finding the location of one string within another are LOCATE, FINDand POSITION
Built-In Functions
Extraction
At times, a programmer will only want part of a string. Any part of a string can be obtained using the RIGHT, LEFT
and MID functions.

The following string manipulation functions are called by typing:


Result = FunctionName(String [,x,y])
Built-In Functions
Concatenation
Concatenation is where two or more strings are joined together to make a single string.
Note that when two strings are added together the second string is added to the end of the first:

 “Peter” + “Jones” = “PeterJones”


 “Peter” + “ “ + “Jones” = “Peter Jones”
 “36.85” + “47” = “36.8547”
 “47” + “36.85” =“4736.85”
 “3/10/03” + “15” = “3/10/0315”
Built-In Functions
Length
Sometimes a programmer will need to know how many characters there are in a string.

Conversion
Strings and numbers
Strings are a sequence of ASCII characters, even if they contain only numbers such as “241”, and so they cannot be
used within an arithmetic calculation – they need to be ‘evaluated’ first.

Likewise a number such as 27.3 is not stored as ASCII characters and so cannot be used within any of the string
functions (such as Left, Right, Mid).
Built-In Functions
The function STR converts a number into a string and VAL converts a string into a number:

Characters and ASCII codes


The following two functions are used to either find the ASCII code for a specific character or to find the character
from the ASCII code:
Built-In Functions
ASCII character codes
Below is a table showing the most common characters and their ASCII codes:
Built-In Functions
Note the following:
 the codes less than 32 are ‘control’ codes that are not used in strings;
 ‘space’ (code 32) has the lowest code;
 next comes most of the punctuation symbols;
 then digits 0–9
 then uppercase letters
 then lowercase letters
 all other characters (e.g. é, å, π, etc.) have codes higher than these.
Built-In Functions
Comparing strings
When comparing strings, the codes of each string are compared, character by character, to decide which string is
greater.

Because it is the ASCII codes that are compared the following applies:

“Computing” <> “computing”


in fact:
“Computing” < “computing”
“10” < “2”
“02” < “1”
“1 120” < “1,120”
“ computing” < “Computing”
Built-In Functions
Sorting filenames
The following table shows a list of inconsistently names music tracks and the order in which they would be sorted:

In order to get them sorted into the required order, they must be renamed with consistent use of uppercase letters,
spaces and leading zeros.

Recommended naming would be:


Track 01.mp3, Track 02.mp3, …, Track 10.mp3, Track 11.mp, …
Built-In Functions
Output data onto screen/file/printer, formatting the data for output as necessary.
Output will be either to the screen, a file or the printer.
Output controls
Output to the screen could be via a dialogue/message box, a text box, a list box or simply direct on the form.
Custom string formatting can be accomplished using specific characters recognized by the Format$ function, shown
in the table below:
Built-In Functions
To demonstrate custom string formats using combinations of the characters listed above, set up another "Try It" project, and place the
following code in the cmdTryIt_Click event of cmdTryIt button:

Private Sub cmdTryIt_Click()


Dim strName As String
strName = InputBox("Please enter your name:")

Print "Using '>':"; Tab(25); Format$(strName, ">")


Print "Using '<':"; Tab(25); Format$(strName, "<")
Print "Using '@':"; Tab(25); "Hello there, "; Format$(strName, "@@@@@@@@@@"); ". How are you?"
Print "Using '&':"; Tab(25); "Hello there, "; Format$(strName, "&&&&&&&&&&"); ". How are you?"
Print "Using '!@':"; Tab(25); "Hello there, "; Format$(strName, "!@@@@@@@@@@"); ". How are you?"
Print "Using '!&':"; Tab(25); "Hello there, "; Format$(strName, "!&&&&&&&&&&"); ". How are you?"
Print "Using '\':"; Tab(25); Format$(strName, "\H\e\l\l\o\,\&&&&&&&&&&\.")
Print "Using embedded quotes:"; Tab(25); Format$(strName, """Hello,""&&&&&&&&&&"".""")
Built-In Functions
Run the project and click the "Try It" button. When the input box appears, enter a name in mixed case (in this
example, Bruce was entered). The strings will be displayed as follows:

You might also like