Download presentation
Presentation is loading. Please wait.
1
1 Identifiers / Variables
Declaring Identifiers/Variables, Overflow 17/01/2019
2
Learning Objectives Explain what a identifier/variable is and what they are used for. Explain how to declare identifiers/variables and explain the necessity for doing so. Explain why using comments is useful, how to enter them and what VB does with them. Explain the Overflow error. 17/01/2019
3
Learning Objectives Explain: What translators do
The process of source-object code The three major error types which will need to be tested The concept of developing a test plan. Black box testing White box testing The concepts of Alpha tests and Beta tests Translator diagnostics Cross referencing Program traces Variable dumps Dry runs (desk checks)
4
Software The general term used to describe all the programs, routines or procedures that run on a computer. Makes a computer do something and are written to run on the hardware. Computer instructions or data. Any instructions that can be stored electronically are software.
5
Software Software Hardware Computer instructions or data.
Makes a computer do something and are written to run on the hardware. Hardware Software
6
e.g. Pascal, Visual Basic, C, Fortran
Software is usually written in a high level language which is fairly similar to our own spoken languages. This makes it easier for us humans to use. However, computers only understand machine code which is in binary form (1s and 0s). Hardware High Level Languages e.g. Pascal, Visual Basic, C, Fortran Machine Code
7
Identifiers / Variables
When a program runs, any data that it uses is stored in RAM. A identifier/variable is a name made up by the programmer to identify the address in RAM where a particular piece of data is stored. 17/01/2019
8
Conventions for Naming Identifiers / Variables
Always use meaningful names / identifiers. You cannot use spaces. Best to follow the convention of making each word start with a capital e.g. DateOfPayment Using the first capital will also help differentiate variable names / identifiers from control names. 17/01/2019
9
Range / Fractional Real Precision Storage Requirements (bytes)
Data Types overflow Main Data Types Data Types Range / Fractional Real Precision Storage Requirements (bytes) Text (Characters) / String in VB Any characters 1 per character Char Any character 1 byte Integer (Numeric, Whole numbers, no fractions) Byte 1 Integer In Access stored by 2 bytes so +/- 32,768. In VB stored by 4 bytes so approx. +/- 2 billion 2 - 4 Long (Integer) In Access stored by 4 bytes so approx. +/- 2 billion. In VB stored by 8 bytes so approx. +/– E+18. 4 – 8 Floating Point (Fractional Real Numbers) Single 7 4 Double 15 8 Decimal 28 12 Boolean (Y/N True/False) Often 1 byte is reserved Date/Time 9
10
Summary of Data Types Storage Requirements
Storage Requirements (bytes) String / Text 1 byte per character Char 1 byte Byte 0 – 255 Integer > 255 4 bytes Decimal / Real 8 bytes Boolean (True/False – Yes/No – 2 answers only) Date / Time 17/01/2019 Note: Use this summary in exam questions. The previous slide is for general interest only. 10
11
Dim Use this statement to declare identifiers/variables.
Dim (Variable name) As (Data Type) e.g. Dim MyName As Text Dim Number As Integer Dim Payment As Decimal Dim DataOfPayment As Date Dim Paid As Boolean Boolean = True or False Dim InsuranceRating As Char Char = One letter only (e.g. A, B or C only). 17/01/2019
12
Declaring Variables Means to tell Visual Basic two things about a variable: Its name or identifier. Its data type. 17/01/2019
13
Working with identifiers / variables
Imagine 3 people: Mr User Ms Programmer Ms Processor (CPU) Ms Programmer and Ms CPU communicate in the Visual Basic programming language (which I will show by underlining).
14
Working with identifiers / variables
Dim FirstNumber As Integer Ms Programmer instructs Ms CPU “Get ready! Later you will either be given an integer or asked to calculate an integer and I want you to call it FirstNumber.”. Ms CPU will now find an empty place (box) in her memory (RAM), reserve it and name it FirstNumber. Similarly: Dim SecondNumber As Integer Dim Total As Integer
15
Working with identifiers / variables
Console.WriteLine("Enter the first number.") FirstNumber = Console.ReadLine Ms Programmer instructs Ms CPU to “Ask Mr User to enter the first number, then store the number Mr User enters in the box you reserved earlier in your memory called FirstNumber.”. Similarly for: Console.WriteLine("Enter the second number.") SecondNumber = Console.ReadLine
16
Working with identifiers / variables
Total = FirstNumber + SecondNumber Ms Programmer then instructs Ms CPU to “Calculate the addition of what you have stored in the boxes in your memory called FirstNumber and SecondNumber, and store the answer in the box you reserved earlier in your memory called Total.”.
17
Working with identifiers / variables
Console.WriteLine("The total is: " & Total) Ms Programmer then instructs Ms CPU to “Display (show) an explanation “The total is:” and the Total so that Mr User can see it.”.
18
Standard Code for a Program using Identifiers / Variables
Declare your variables (one for each data entered and one for a result): Dim VariableNameToStore1 As (DataType) Dim VariableNameToStore2 As (DataType) … Dim VariableNameToDisplay As (DataType) Ask the user to store data entered by a user: Console.WriteLine(“Message1.") VariableNameToStore1 = Console.ReadLine Console.WriteLine(“Message2.") VariableNameToStore2 = Console.ReadLine Formulae: VariableNameToDisplay = VariableNameToStore1 +-*/ VariableNameToStore2 Display: Console.WriteLine(“AnswerMessage: " & Total) 17/01/2019
19
Code Comments All programs must contain comments.
As programs become more complicated it is useful to be able to write explanations of the logic of each line of code but obviously we want VB to ignore them. This is achieved by using apostrophes ‘. All programs must contain comments. 17/01/2019
20
Program 1a Add two numbers
Specification: Allow the user to enter two numbers and display the sum. 17/01/2019
21
Program 1a Add two numbers
Launch Visual Basic and create a “New Project”. 17/01/2019
22
Program 1a Add two numbers
Click “Console Application”, name the new project “Add two numbers” and click “OK”. 17/01/2019
23
Program 1a Add two numbers
Click “Save All” and click “Save”. Choose a different location if necessary. See “Useful VB settings”. 17/01/2019
24
Program 1a Add two numbers
All code (at least for now) should be typed in between: Sub Main () Type all code here. End Sub 17/01/2019
25
Program 1a Add two numbers Context-Sensitive Prompts
Start writing the following code: Console.WriteLine("Enter the first number.") Notice the “context-sensitive prompts” as you type. 17/01/2019
26
Program 1a Add two numbers
Finish writing the following code: Console.WriteLine("Enter the first number.") FirstNumber = Console.ReadLine Console.WriteLine("Enter the second number.") SecondNumber = Console.ReadLine Press enter or click into another line so VB can check your code. Note that there will be errors (blue squiggly lines) and if you point to them you will get a “translator diagnostic”, please move onto the next slides for an explanation. 17/01/2019
27
Program 1a Add two numbers
You will get a blue squiggly line underneath the identifier FirstNumber. Hover over this and you will get a message saying ‘Name ‘FirstNumber’ is not declared’. Why? The variable has not been declared! See the next slide. 17/01/2019
28
Syntax Errors While you are writing in what we call the “Integrated Development Environment (IDE)” if you get blue squiggly lines underneath your procedure code, then there is a syntax error. Errors in a program that break the grammar rules of the language being used. The IDE constantly checks that the rules of the language are being followed as you write; this makes this initial error detection “dynamic”. This could be due to many reasons but the following are the most common: You have used a name that does not exist. You have misspelt a reserved or keyword and VB does not recognise it (it should offer you suggestions like a spell check if you right click the error). You have misused a reserved or keyword. A reserved or keyword is any word in the vocabulary of a programming language which can only have the meaning defined in that language. Also, as noted on the previous slide, VB will give you suggestions as soon as you start typing. Use these suggestions to save your fingers and time! Other types program errors.
29
Translator diagnostics
The translator looks up each word from a program in a dictionary. The dictionary tells the translator program what the rules are for that particular word. A wrongly typed word will not appear in the dictionary. If rules governing how it should be used have not been followed properly, the translator will know that there is something wrong. Either way, the translator program knows that a mistake has been made, it knows where the mistake is and, often, it also knows what mistake has been made. Other types program errors.
30
Translator diagnostics
Messages detailing syntax errors sent to the programmer and usually giving hints as to what to do.
31
Program 1a Add two numbers
Delete the lines of code you entered previously. Now enter the following code: Dim FirstNumber As Integer ‘Declares a variable for the 1st number. Dim SecondNumber As Integer ‘Declares a variable for the 2nd number. Dim Total As Integer ‘Declares a variable for the sum of the 2 numbers. Press enter or click into another line so VB can check your code. 17/01/2019
32
Program 1a Add two numbers
You will get a green squiggly line underneath the variable name FirstNumber. Hover over this and you will get a message saying ‘Unused local variable: ‘FirstName’’. Why? VB is simply trying to help by informing you that you have declared a variable but have not used it in your code yet. 17/01/2019
33
Words that cannot be used as identifiers
Experiment using different words as identifiers: e.g. Total Price Of Order Must not contain any spaces. Total:Price Must not contain punctuation characters. Sum&Price Must not contain certain special symbols. 5Totals Names must begin with a letter. But note that T5otals, Totals5, etc… are acceptable as numbers can be used, just not at the beginning. Date Names can’t be keywords or reserved words which are words special to the language and have defined meanings for that language. e.g. Dim Date As Date cannot be used the word Date is a data type and already has meaning. 17/01/2019
34
Program 1a Add two numbers
Enter the following code after the declarations you have already: ‘Ask the user to enter the first number. Console.WriteLine("Enter the first number.") ‘Store the number entered into the variable FirstNumber. FirstNumber = Console.ReadLine ‘Ask the user to enter the second number. Console.WriteLine("Enter the second number.") ‘Store the number entered into the variable SecondNumber. SecondNumber = Console.ReadLine ‘Calculate the total. Total = FirstNumber + SecondNumber ‘Display a message and the total. Console.WriteLine("The total is: " & Total) 17/01/2019
35
Program 1a Add two numbers
Enter the rest of the following code: 17/01/2019
36
PrettyPrint Auto-formats: Keywords to light blue.
e.g. Dim, As, Integer, Input/Output Keywords to soft blue. e.g. Console String characters to red. e.g. "Enter the first number.“ Comments to green. e.g. 'Declares a variable for the 1st number. 17/01/2019 What to send me?
37
Translators Translate high level languages (the translator’s source code) into machine code (the translator’s object code) which can be executed by a computer. Translators High Level Languages Machine Code Source Code Object Code written in a high level language. Code in executable form.
38
Program 1a Add two numbers
Run / Translate (Ctrl + F5) and test the program. You can also install your program and produce a “Setup” executable that anyone can use to install your program. Project menu - Publish Finish Double Click “setup”. Install In school you will only be able to install on your own account. We will not do this for every program though, only here to show that you can. 17/01/2019
39
Where & how are programs saved?
All programs are stored as folders either: By default in “My Document” – “Visual Studio 2010”. Or If you have followed the “Useful Visual Basic Settings” or otherwise changed the default settings, then in the folder you have set. To open a program double click VB10 icon with Program’s name that you see in the Program’s folder: Note that doing this allows the opening of more than 1 program at a time (opening through the VB environment does not). Remember though that for a program to open all other files and folders in this initial Program’s folder are needed, so if you wish to a program then you will need to compress the entire Program’s folder. However, only me a program’s folder if I specifically request you to do so. See next slide for what you will normally send me.
40
What to send me? When sending me your work I will ask for a “PrettyPrint” printout of your code only. Copy and paste the entire code (Ctrl+A, Ctrl+C, Ctrl+V) into a Word document or any other Word Processor, print it to Adobe and send me this Adobe printout file. To print to Adobe .pdf at home install doPDF for free.
41
FirstNumber = Console.ReadLine
In programming “=”, in this case, is an arithmetical operator meaning to assign. It does not mean “it is equal” it means “make it equal”. Left Side -> Right Side (make it equal to) 17/01/2019
42
Program Development Testing: Debugging: Are there any errors (bugs)?
Where is the error (bug) and what is causing it? Solve the error (bug).
43
Test Plan A schedule drawn up which contains a test for every type of input that could be made and methods of testing that the program actually does what it was meant to do.
44
Alpha Testing Performed by the programmers involved in writing the program. Focus on error free processing.
45
Black box testing Use of different input values to determine whether the program gives you expected results (compare actual results with expected ones) and can cope with them without crashing. These values should include Different types of input e.g. Typical values Borderline values Unacceptable values Do not look into the program (box) all you see are the inputs (what goes in) and outputs (what comes out at the end). Logic / Arithmetic Errors
46
Example 1 of Black Box Testing
A program which uses marks out of 100 from a math's examination as input. Normal data like: 27, 73.., Borderline data: 0 and 100 Invalid data like: –34, 123, Note that you should try one piece of invalid data at a time otherwise, if there is an error or problem, you will not be able to tell which piece of invalid data is causing the problem (one, more than one or all). For example using means that, if there was an error, you would not know if it was because you used a negative (-) number or because you used a decimal (real) number. You should use -16 and then (in any order) first, if there are no errors, then you could try Logic / Arithmetic Errors
47
Example 2 of Black Box Testing
A program to work out the mean of three numbers. 1, 2, 3 Will integers give an integer answer? 1, 2, 4 Can the software cope with a recurring decimal answer? (Note that “1, 2, 4 to test a different set of integers” would not get a mark because the reason for the test is not different) 1, 2.5, 3 Can the program handle decimal inputs? 1, 2½, 3 Are fractions allowed? -1, -2, -3 Can negative numbers be handled? 1, 2 What happens when only two values are input? Logic / Arithmetic Errors
48
Debugging Tools Debugging tools to allow programmers to investigate conditions where errors occur. The following slides describe some debugging tools. 17/01/2019 Logic / Arithmetic Errors
49
White Box Testing / Dry Runs / Desk Checking
The user works through every logical path of the program instructions manually, keeping track of the values of the variables. Most computer programs require a very large number of instructions to be carried out, so it is usual to only dry run small segments of code that the programmer suspects of harboring an error. Testing knowing the code. Testing the structure and logic of all the algorithms within the code. Known as “white box” as testing is done by looking at the code so the program is like a transparent box. Examines the program code (white box). 17/01/2019 Logic / Arithmetic Errors
50
Traces / Variable Watch
A trace is where the program is run and the values of all the relevant variables are printed out, as are the individual instructions, as each instruction is executed. In this way, the values can be checked to see where they suddenly change or take on an unexpected value. For how to do this in VB - see next two slides. 17/01/2019 Logic / Arithmetic Errors
51
Traces / Variable Watch
Logic / Arithmetic Errors Switch over to see the your code. Press F8 to ”step into” or run the program line by line. Basically press F8 repeatedly to run each line, the “next line” to be executed or run is highlighted in yellow. In the program in this presentation you will need to enter numbers and click the “Enter” button to get things started. Note the highlighted line is next it does NOT mean the line just run (that would be the previous line). F8 17/01/2019
52
Traces / Variable Watch
Logic / Arithmetic Errors Debug menu – Windows – Locals. For only specific variables: Debug - Watch – Right Click the variables required and “Add Watch”. Just point to each variable to see its value. OR Then press F8 repeatedly to execute each line and watch the values of the variables change (as each line is run. Variables/expressions Report Window 17/01/2019
53
Manual White Box Testing / Dry Runs / Desk Checking
Logic / Arithmetic Errors Manual White Box Testing / Dry Runs / Desk Checking Basically manually Tracing or Variable Watching with a table which the programmer fills in. FirstNumber SecondNumber Total 17/01/2019
54
Break Points / Variable dumps
At specified parts of the program, the values of all the variables are displayed to enable the user to compare them with the expected results. This enables the programmer to see where sudden, unexpected changes occur. To do this in VB click the line/s (in the grey column on the left) you wish the program to stop on (the break point/s). Press Play (not Ctrl+F5) and when the program stops, look at the values of each variable as in Variable Watch (see previous slides). Note that the program will not run the line you choose until you press F8, so ideally you should choose the line after the actual line you are interested in. You can also press F8 as before to run the program line by line from a break point. 17/01/2019
55
Cross-referencing This software checks the program that has been written and finds places where particular variables have been used. This lets the programmer check to make sure that the same variable has not been used twice for different things. In VB use Ctrl+F. 17/01/2019
56
Debugging Tools Use these debugging tools, on any program in the future, when you need to find out where errors are and what is causing them. 17/01/2019
57
There are three types program error (bug)
58
1. Syntax errors Covered previously on slides 28 & 29.
59
2. Logic errors (also known as run-time errors if found when a program is run)
A mistake in the way the program solution has been designed. e.g. An instruction in a program may tell the computer to jump to the wrong part of the program. Total_number = Previous_total – New_number Known as logic errors if found whilst not running a program and using white box testing. See earlier on slide 50. Known as run-time errors if found when actually running a program. Black box or white box testing – see slides 42 & 46 .
60
3. Arithmetic Errors (also known run-time errors if found when a program is run)
Inappropriate use of arithmetic. E.g. dividing by zero Known as arithmetic errors if found whilst not running a program and using white box testing. See earlier on slide 50. Known as run-time errors if found when actually running a program. Black box or white box testing – see slides 42 & 46.
61
Beta Testing Testing carried out by the users of the program.
Eventually, the company will want ordinary users to test the program because they are likely to find errors that the programmers did not find. Focus on usability, functionality, and performance.
62
Advice for writing programs
Declare your variables (one for each data entered and one for a result): Dim VariableNameToStore1 As (DataType) Dim VariableNameToStore2 As (DataType) … Dim VariableNameToDisplay As (DataType) Ask the user for data and store data entered into their appropriate variables: Console.WriteLine(“Message1.") VariableNameToStore1 = Console.ReadLine Console.WriteLine(“Message2.") VariableNameToStore2 = Console.ReadLine Formulae: VariableNameToDisplay = VariableNameToStore1 +-*/ VariableNameToStore2 Display: Console.WriteLine(“AnswerMessage: " & Total) 17/01/2019
63
Summary of advice for writing programs
Declare your variables (the number of text boxes + 1 for the result). Ask & Store (the data entered into the appropriate variables). Calculate (Result = …. +-/* etc..). Display (Console.WriteLine(“….. : " & Total)). 17/01/2019
64
Arithmetic & Order of Precedence
Operator Visual Basic Order of precedence Exponentiation (e.g. 102 = 10^2 ) ^ 1 Negation - 2 Multiplication * 3 Division / Integer Division (produces a whole number by removing any decimal parts) INT 4 Modulus (gives a remainder after division e.g.12 Mod 5 = 2) Mod 5 Addition + 6 Subtraction
65
Implicit Variable Use You do not actually have to explicitly declare variables, you can implicitly declare variables by simply using them in your code. However, it is good programming practice and efficient to do so as certain errors/problems can occur if you don’t: Naming-conflict errors – using a variable name/identifier which VB already uses for its own purposes. Spelling mistakes – spelling a variable name/identifier one way the first time you use it and then accidentally spelling another way later in the code. VB assigns the Object data type if the data type of a variable is not declared – this is slower to access and uses more memory. 17/01/2019
66
Option Explicit On - VB looks for undeclared variables as you type in the code (so forcing you to do so). Off – VB does not look for undeclared variables as you type in the code but runtime errors may occur (as described on the previous slide). It is On by default, you can check it is on by: On the Tools menu, choose Options. Open the Projects and Solutions node. Choose VB Defaults. 17/01/2019
67
Overflow Run the program and try entering the number 3000000000
You will get an Overflow error. This is caused by the variable being asked to hold a number outside its Data Type’s range. Have a look at the table on slide 5. 17/01/2019
68
Constants Used when: e.g. Const TaxRate = 0.25
The user does not provide the value. You don’t want the value to change during the program. e.g. Const TaxRate = 0.25 If you try to assign another value to a constant later in the program a error will result.
69
Pseudocode A general code form that represents a generalised form of any programming language. Allows programmers to plan or write code without worrying about any particular languages specific syntax.
70
Pseudocode will use the following data types:
INTEGER, REAL, CHAR, STRING, BOOLEAN, DATE
71
Pseudocode will use the following structures:
DECLARE <identifier> : <data type> declaration CONSTANT <identifier> = <value> <identifier> ← <value> or <expression> assignment INPUT <identifier> OUTPUT <string> OUTPUT <identifier (s)>
72
Extension Programs 1b - h
Change the program to add three numbers. Someone to enter an original price and a percentage discount. The program should display how much they should actually pay. A seller to enter a cost price and a required percentage profit. The program should display the selling price required. Extension: Include VAT of 17.5%. Someone to enter an amount of money placed in a high interest account and a number of years to leave it there. The program should display how much money they will receive after that time (10% per year). Write a program for a motorist who wishes to work out how many kilometres per litre their car is doing. Someone to enter their income, personal allowance and tax rate. The program should display how much tax they should pay. For the moment, until the next presentation “2.1 If Selection”, please assume the user always has a salary higher than the personal allowance. Someone to enter the number of hours worked, normal rate per hour, number of hours overtime (assume overtime rate is double normal rate). The program should display their salary. 17/01/2019
73
Extension “/, DIV or MOD” Program 1i
Raul writes software for a melon packing plant. Raul has Y melons which are to be packed into boxes. Each box contains X melons. Write a program to accept: How many melons are to be packed. How many melons each box contains. And then calculates: The number of boxes as a decimal (if appropriate). The number of full boxes. The number of melons left over. Use each of “/ , DIV or MOD” and decide for yourself which one is suitable for each of the calculations above by trying each one (make sure you know what to expect though, before you entering your numbers). For / / as normal. For DIV Int (….. / …. ) as VB uses the term “INT” rather than “DIV” as CIE does. For MOD …. Mod …
74
Plenary Explain what a variable is and what they are used for.
A variable is a name made up by the programmer to identify the address in RAM where a particular piece of data is stored. To store data for later use. 17/01/2019
75
Plenary Explain why using comments is useful, how to enter them and what VB does with them. They explain the logic of the code both to programmer to help writing and debugging and to any reader of the code. Use ‘ at the end of a line before a comment. Comments are ignored by VB. 17/01/2019
76
Plenary Explain how to declare variables and explain the necessity for doing so. Dim (Variable name) As (Data Type) If you do not declare variables VB will not what know what to do with a name it does not recognise and runtime errors will occur. Explain the Overflow error. This is caused by the variable being asked to hold a number outside its Data Type’s range. 17/01/2019
77
Plenary What is: Source code? Code written in hll. Object code? Code in executable form Machine code? Code in binary form. What is the process which connects source and object code? A translator turns the source code into the object code.
78
Plenary Explain how the translator program prepares the programmer’s code into a program that the machine can run. Translator program turns source into object. Spots some of the errors in the source code. Wrong (reserved) words Wrong syntax in instruction construction Reports errors to user.
79
Plenary State the meaning of the following types of testing.
White box testing. Testing all possible routes through the program logic/Testing knowing the code/Test the algorithm. Note: not dry run on its own Black box testing. Test that the outcome is as expected for a given input/Testing not knowing the code Alpha testing. Testing by programmer/in-house Beta testing. Testing by public/end users/potential users/unconnected with writing
80
Plenary State three types of program error and give an example of each. Syntax error Mistyping a reserved word, e.g. typing plint instead of print Logic error A jump instruction that tells the computer to jump to the wrong place Arithmetic error Inappropriate use of arithmetic. Dividing by zero
81
Plenary Describe the techniques that can be used to help debug a program.
82
White Box Testing / Dry Runs / Desk Checking
The user works through the program instructions manually, keeping track of the values of the variables. Most computer programs require a very large number of instructions to be carried out, so it is usual to only dry run small segments of code that the programmer suspects of harboring an error. Testing knowing the code. Testing specific algorithms within the code. Known as “white box” as testing is done by looking at the code so the program is like a transparent box.
83
Cross-referencing This software checks the program that has been written and finds places where particular variables have been used. This lets the programmer check to make sure that the same variable has not been used twice for different things.
84
Traces A trace is where the program is run and the values of all the relevant variables are printed out, as are the individual instructions, as each instruction is executed. In this way, the values can be checked to see where they suddenly change or take on an unexpected value.
85
Variable dumps At specified parts of the program, the values of all the variables are displayed to enable the user to compare them with the expected results.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.