_Programming_A_level_comp_science
_Programming_A_level_comp_science
SECTION 7.7
Programming
Programming is the process of creating a set of instructions that tell a computer how to
perform a task. Programming can be done using a variety of computer "languages," such as
SQL, Java, Python,VB.Net and C++.
A programming language is a vocabulary and set of grammatical rules for instructing a
computer or computing device to perform specific tasks. The term programming
language usually refers to high-level languages, such as BASIC, C, C++, COBOL, Java,
FORTRAN, Ada,Python and Pascal.
They are problem oriented i.e. each HLL has structures and facilities appropriate to a
particular type of problem, e.g. FORTRAN (FORmula TRANslation) and ALGOL
(ALGOrithmic Language were developed for scientific and engineering problems,
BASIC (Beginners All purpose Symbolic Instruction Code) was developed as a teaching
language.
They are portable which means that a program written for one machine will run on any
other machine for which the appropriate compiler and interpreter is available.
Statements in HLL resemble English like statements or mathematical expressions and
they are easier to learn and understood than assembly language.
Each statement in HLL will be translated into several machine code instructions
Facilities of HLL
Selection structures such as if...then..else, SELECT CASE statements
Iteration structures such as while...do
Built in routines to simplify input and output (readline, writeline in VB.Net console
Built in functions such as sqr, log, chr,msgbox,input box etc.
Data structures such as string, record
Types of HLL
1. Business language – COBOL
2. Scientific language – FORTRAN and ALGOL
3. Educational language – PASCAL,BASIC and LOGO
4. System programming – C
5. Object oriented programming – C++, DELPHI, Smalltalk,VB,Net,Java
6. Artificial Intelligence – PROLOG
Bank Account
Account number
Customer Name Data
Balance
Credit on amount
Debit on amount
Provide the balance methods /operations
Provide the customer details
An object is group of data and associated program routines used within an object-
oriented programming system.
Inheritance is the means by which the properties and methods from the object class are
copied to the object being created so that only the difference have to be reprogrammed.
A derived class is a class resulting from the inheritance process. It have all the features of
the parent class plus any new features specified.
Two classes that are derived from the same base are said to be polymorphic.
Polymorphism means that two object may share many characters but have unique
features of their own.
Objects in Windows
An object is an independent procedure that contains both the instructions and data to
perform some task, and the code necessary to handle various messages it may receive.
Objects in windows include forms, dialogue boxes, command buttons, list boxes and text
boxes
An object contains all that is needed to make that particular aspect of the program carry
out bits task:
The procedure (methods) that are needed to respond to events that may occur
The data that is needed by the procedures.
The process of bundling together procedures and data is referred to as encapsulation.
Data Methods
Name: Button 1 OnClick
Text: Press Me OnDragDrop
Height: 41 OnDragOver
Tab Stop: True OnEnter
Visibility: True Inheritance diagram OnExit
Width: 121
MAMMAL CLASS
Properties Methods
Age Eat
Gender Breathe
Body Temperature Sleep
(Inherits these properties and methods) (Inherits these properties and methods)
Properties Methods Properties Methods
Age Eat Age Eat
Gender Breathe Gender Breathe
Body Temperature Sleep Body Temperature Sleep
Declarative languages
e.g. Prolog (PROgraming in logic)
In declarative languages, the computer is told what the problem is, not how to solve it.
It consists a set of facts and rules about a particular thing rather than a sequence of
instructions.
The languages are useful when solving problems in artificial intelligence, such as medical
diagnosis or fault finding in applications.
Characteristics of Prolog
Instead of defining how a problem is solved, the programmer states the facts and rules
associated with the problem.
The order in which the facts and rules are stated is not important, unlike the statement in
imperative language.
It is easy to add new rules, delete or change existing rules.
The route through the program follows does not have to be stated by the programmer,
Prolog will select a possible route through a program and if that fails, it will backtrack to
that pointand try another route.
NB
Clause 1 to 10 are facts
Clause 11 and 12 are rules
A capital letter denote a variable.
1) Constants
Is a data item associated with a location in memory, once a value is assigned to it, it
cannot be changed while the program is running.
Constant must have an identifier name and a declared data type, e.g. Pi is an identifier
name for a constant that is assigned a value.
Syntax
Const <variable> As <data type>=”value”
Const Pi As Single
Pi = 3.141593
Constant are useful as they can be referred to many times in the program code by their
identifier name.
2) Variable
It is a data item associated with a location in memory. The value of the variable may
change during the running of the program.
The variable is given an identifier name, e.g. Noofchildren is an identifier name.
Variables can be local or global.
Variables are declared using the keyword Dim
Syntax
Dim <variable> as <data type>
Example
Dim x as integer
Global variables
Are identifiers which are declared outside the main program.
Can be used throughout the program and all subprograms.
A global variable can be accessed and modified from anywhere within the system.
Example
Module module 1
Dim area,radius as single
Const pi as single
pi.=3.14
Sub main( )
console.writeline(“Enter radius”)
radius= console.readline( )
if radius>0 then
area.=pi*radius*radius
Else
Console.writeline(“Please enter value above zero”)
Console.readkey()
End if
End sub
- In the above program the variables are area,radius, and pi because they are declared
outside the Sub main()
- These variables are refered to or used in the sub main()
Area Of Circle
Enter Radius
if radius>0 then
area.=pi*radius*radius
Else
Msgbox(“Please enter a value above zero”)
End if
End sub
End Class
Local variables
A variable which is inside a procedure or function.
They exist only during a call to the subprogram
Example 2
- The below program impliments the use of local variables in console application
- Note that the variables are now inside the sub main() ,this shows the declarations and
use of local variables.
Module module 1
Sub main( )
console.writeline(“Enter radius”)
radius= console.readline( )
if radius>0 then
area.=pi*radius*radius
Else
Console.writeline(“Please enter value above zero”)
Console.readkey()
End if
End sub
3) Expression
Is when numbers,symbols and operators grouped together that show the value of something
eg 4x-7.
An expression is a collection of two or more terms that perform a mathematical or logical
operation. The terms are usually either variables or functions that are combined with an
operator to evaluate to a string or numeric result.
Identifier
Is a name that is used to represent a variable, constant, a function, a procedure, an object
or any other element in a program.
Scope of identifier
The scope of identifier defines the extent to which an identifier is potentially accessible
within a system.
4) Statement
Is a program instruction written in high level language that is human readable and it can
be executed.
When a statement is translated, it often generates several machine-code instructions
It is an instruction written in high level language that commands the computer to perform
specifc action.
Programming statements
Assignment Spaces=Spaces -1
A=A+5
Iteration FOR Count= 1 to 10
Msgbox(count)
NEXT
Do
Msgbox(count)
Count=count +1
Loop Until count>10
While count<10
Msgbox(count)
Count=count +1
Endwhile
Do until count>10
Count=count +1
Msgbox(count)
Loop
Assignment statement eg
Textbox1.text=textbox2.text
Textbox1.text=button1.text
X=x+1
Checkbox
A control for selecting from give options
Syntax
Controlname.property=<bolean value>
Eg.
Chkbox1.checked=true
Programming constructs
Are used in structured programming to support the Top-down approach applied when
developing an algorithm.
Programming constructs are used in program flowchart and pseudocode.
There are three programming constructs;
Sequential construct – They execute one or more statements or instructions one
after the other i.e. in sequence.
6) Control structure
It is a block of programming that analyses variables and chooses a direction in which to go
based on given parameterseg If -----Then --End if
console.writeline(“Enter radius”)
radius= console.readline( )
if radius>0 then
area.=pi*radius*radius
Else
Console.writeline(“Please enter value above zero”)
Console.readkey()
End if
STRUCTURED PROGRAMMING
SELECTION
Selection arises when a condition exists in a problem and you need to take a decision or make a
choice.
In Visual Basic, a condition is coded by using a data name (or a variable) which compared with a
value or a text, depending on whether the variable is numeric or string.
Types of selection
Simple selection
Binary selection
Multiple selection
Relational operators
Simple Selection
Syntax IF condition THEN
Statement
Endif
Answer
Rem Declare Variables
End Sub
Binary Selection - Format 1
Syntax IF condition THEN
Statement(s)
Else
Statement(s)
ENDIF
Question
A manager pays his staff members a car allowance depending on the size of their
cars. If the engine size is less than or equal to 1300 cc, an allowance of $10 per mile
is paid. If it is greater, an additional Rs 5 per mile is paid. Write a program that will
input number of miles travelled and the engine size. Calculate and print the car
allowance received by the staff members.
Answer
Rem declare variables
End Sub
Dry run the program with the following data and write the expected result
Activity 1
Write a program to input product code, quantity and price. Calculate total cost. A message
is displayed whether to allow a discount or not on the total cost depending on its amount
as shown in the above table. Write a program to perform this task.
Syntax
OR AND
OR Syntax AND Syntax
IF (condition 1) OR (condition 2) THEN IF (condition 1) AND (condition 2) THEN
Statement(s) Statement(s)
ENDIF ENDIF
NB: You can have any number of conditions combined with OR and AND.
The following tables shows the result from separating 2 conditions using AND and OR
AND OR
are TRUE
Activity
The following table shows the amount of tax payable based on the disposable income.
Disposable Income Tax Rate
15000 – 30000 10%
30001 - 50000 20%
> 50000 30%
Write a program to input the disposable income. Calculate and print the tax payable/
NESTED IF...ENDIF
The nested IF... ENDIF structure provides an easy method to code a problem with multiple
conditions insted of using too many OR / AND operators
Syntax IF condition(s) THEN
Statement(s)
ELSEIF condition(s) THEN
Statement(s)
ELSEIF condition(s) THEN
Statement(s)
ElseIf...
ELSE
Statement(s
ENDIF
SELECT...CASE STRUCTURE
In situations where you have too many conditions concatenated by either using logical operators
(OR/AND) or nested IF structure which makes your program longer, then the SELECT...CASE is
another way to do the job.
Syntax Select CASE variable
Case conditions
Statement(s)
Case conditions
Statement(s)
Case Else (match not found for above conditions)
Statement(s)
End Select
End Select
End Sub
CHECK BOX
A Check Box provides a way to make choices from a list of items. You can select several, all, or none
of the items at one time.
Properties Effect
Caption Set the text to display beside the check box
Font Sets the font type
Note:
Frames are useful to regroup control buttons and make the screen more presentable
You must insert frame first and the insert controls inside it.
Create the following form
Frame 1
Text Boxes (1-4)
Label 1 Option Buttons (1-4)
Labels(2-5)
Frames (2-4)
Labels properties
Label 1
Name : lblTitle
Autosize: True
Boarder Style: Fixed Single
Caption: Members Information
Font: Ms Sans Serif Regular 18
Alignment: 2-Center
Frame properties
All frames have the property: 1-Fixed Single for Border Style
- MS Sans Serif 12 , Bold for font
Group box 1 Name :frmPersonal
Text :Personal Information
Group box 2 Name :frmSex
Text :Sex
Group box 3 Name :frmStat
Text :Status
Group box 4 Name :frmMeal
Text :Meal
A list box that contains the list of possible data which you define and from which you have to
pick one data item at run-time.
Design a form (Login) that will request for a password. If the password is correct, another form is
given, otherwise an error message is displayed.
Combo box
Properties
Form Properties
Name :frmLogin
Border Style :1 – Fixed Single
Caption :Login
Startup position:2 – CenterScreen
Label properties
Label 1
Name :lblUser_name
Caption :&User Name
Label 2
Name :lblPassword
Caption :&Password
Command button 2
Name :cmdQuit
Caption :&Quit
Main Form
Label properties
Name :lblTitle
Alignment :Center
Command properties
Name :cmdClose
Caption :Close
Fontsize :12
Code
Private Sub Form_Load()
'does the initial setup of the screen and defines what data
'the control box should provide
With cboUser_name
.List(0) = "Administrator"
.List(1) = "nooreen"
.List(2) = "abdal"
End With
End Sub
End Sub
REPETITION – ITERATION
TYPES OF REPETITION
For ...Next
Syntax For counter = initial value Tofinal value
Instructions
Next counter
Instructions
Activity 1
Write a program using For ... Next that will output the integers from 1-5
Solution
Open a form with the following properties
Name :frmoutput
Caption :List Numbers
Activity 1
Write a program to print the even numbers less than 20
Solution
Open a form with the following properties
Name :frmEven
Caption :Even Numbers
Compiled byPrivate
ChiseseSub
L Form_Load ( ) 0772 563 672
26 July 2021 Frmeven.Show [email protected]
For counter = 1 – 5
Print Counter
23
Activity
Write a program using Do While ... Loop that will output the integers from 1-5
Solution
Open a form with the following properties
Name :frmList
Caption : Numbers
Write a program using Do... Loop Until that will output the integers from 1-5
Solution
Open a form with the following properties
Name :frmListintegers
Caption : Integers
Practise Questions
1. Write a program that will input 5 numbers. Calculate and print the total and average of these
numbers.
2. Write a program to input a number. Print the arithmetic table for that number.
3. A quality control inspector tests ovens by setting them to 200o and the measuring the actual
temperature inside the oven five times at ten minute intervals. Write a program to input the five
measurement and then print
a) The average temperature
b) The maximum temperature
c) The minimum temperature
During the test period.
4. Write a program that will enable you to input a password and output a message to inform you
whether it is correct or not. If you enter a wrong password, you will be given the chance to enter
it again up to a maximum of 3 times.
ERRORS IN VB
A bug is an error in the code which can prevent your program from running properly.
Debugging is the process of finding and removing errors.
The debug toolbar and Debug menu provide aids in tracking down logic errors.
Types of error
There are three types of errors:
Syntax errors – is a mistake in the grammar of Visual Basic. Examples include misspelling
keywords (e.g. Lop instead of Loop, forgetting an End If, an opening parenthesis without a
closing parenthesis.)
Run-time errors – causes the program to stop working. Example is trying to store a number that
is too big for a number (e.g. integer values can store up to 32767, if you try to store a number
bigger than this will cause overflow), attempting to divide a number by zero, trying to open a file
which is already open
Logic or semantic errors - error results from a mistake in the logic of your program code.
Examples are using the wrong logical operators (AND/OR) in loop conditions or assigning an
incorrect value to a variable or to use a wrong arithmetic symbol e.g. a + b instead of a - b.
Subroutine
A subroutine (function, procedure or subprogram) is a portion of code written in a larger
program which performs a specific task and relatively independent of the remaining code.
High level languages(HLL) provide libraries of useful pre-written programs, which are
termed pre-defined procedures and functions.
They have previously been written, compiled and tested so that they can be used by
programmers.
Procedure
Is a type of subroutine which is called by main program by writing its name followed by
any parameter passing within the brackets.
Parameter are passed by values or by reference.
A procedure can have one or more parameters, usually referred to as the parameter list.
This act as an interface between the calling programs and the procedure.
Procedure Declarations
Example
Consider the following problem.The user enters two numbers and the algorithm outputs their
product.
Solution one
Product
Solution 2
num1 = 5.5
num2 = 4.0
End Sub
Solution 3
Using procedures
8. ExplainPurposeofProgram()
9.
10. num1 = 5.5
11. num2 = 4.0
12.
13. product = num1 * num2
14. OutputResult(num1, num2, product)
15. End Sub
16.
17. Sub ExplainPurposeofProgram()
18. MsgBox("The purpose of this program is to display two numbers and their_
19. product", , "Purpose")
20.
21. End Sub
22.
23. Sub OutputResult(ByVal FirstNumber, ByVal SecondNumber, ByVal Result)
24. MsgBox("The product of" & FirstNumber & "and" & SecondNumber & "is" &
Result,_ , "Result")
27. End Sub
28.
29.End Class
Procedure arguments
Procedure interface(header)
Function
Is also a type of subroutine.
A function can accept parameters and return a single value.
The name of the function is used as a variable having that value.
Function calls appears in programs as expressions.
The function has to contain an assignment to give its value.
The function type has to be specified.
A function can be maintained separately from the main program that allows different
programs to use them.
A function start with a function header.
A function is not normally used when more than one value is to be passed back
Procedure Functions
1. Returns more than one value. 1. Returns a single value
2. Is called by calling program by 2. The name of the function is used as a
writing its name, followed by an variable having that value
parameter passing within the brackets. 3. Function calls appear in the calling
3. program as an expression.
4. Starts with a function header
Function declaration
Parameter Passing
A parameter is a means of passing information to and from a procedure.
Parameters can be of two types:
Formal parameters: These are declared within the procedure heading.
Actual parameters: These are parameters which are passed in the call statement of
the main programs.
Any identifier whose value will be changed in the subprogram must be declared as a
variable using the var statement. These are called variable parameters and they provide
a two way communication.
Parameters whose values do not change in the subprogram are called value parameters.
They provide one way transfer of data from the main program to the procedure.
Parameter can be passed by:
Passing by value: the actual value is passed and the original value is retained when
subroutine is finished.
Passing by reference: the address of the values is passed and any change to the value
of the parameter in the subroutine changes the original value.
Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array is
used to store a collection of data, but it is often more useful to think of an array as a collection
of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
1. one-dimensional array
2. two-dimensional array.
A one-dimensional array is like a list of items or a table that consists of one row of items or
one column of items.
To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Table 16.1. One dimensional Array
Student
Name(1) Name(2) Name(3) Name(4)
Name
Example 1
Dim studentName(1 to 10) As String
Dim num As Integer
Private Sub addName()
For num = 1 To 10
studentName(num) = InputBox("Enter the student name","Enter Name", "", 1500, 4500)
If studentName(num)<>"" Then
Listbox1.item.add( studentName(num))
Else
End
End If
Next
End Sub
A two-dimensional array is a table of items that make up of rows and columns. The format
for a two dimensional array is ArrayName(x,y) and a three-dimensional array is
ArrayName(x,y,z) .
To declare an array in VB.Net, you use the Dim statement. For example,
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Chipo", "Tatenda", "Tapiwa", "Tadiwanashe", "Paddington"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
Example 2
In this example, we want to summarize the first half-yearly sales volume for four products.
Therefore, we declare a two dimension array as follows:
Besides that, we want to display the output in a table form. Therefore, we use a list box. We
named the list box listVolume. AddItem is a listbox method to populate the listbox.
The code
Private Sub cmdAdd_Click()
Dim prod, mth As Integer ' prod is product and mth is month
Dim saleVol(1 To 4, 1 To 6) As Integer
Const j = 1
listVolume.Item.add (vbTab & "January" & vbTab & "February" & vbTab & "March" _
& vbTab & "Apr" & vbTab & "May" & vbTab & "June"
listVolume.AddItem vbTab & "____________________________________________"
For prod = 1 To 4
For mth = 1 To 6
saleVol(prod, mth) = InputBox("Enter the sale volume for" & " " & "product"
& " " & prod & " " & "month" & " " & mth)
Next mth
Next prod
For i = 1 To 4
listVolume.AddItem "Product" & "" & i & vbTab & saleVol(i, j) & vbTab & saleVol(i, j + 1)
& vbTab & saleVol(i, j + 2) _
& vbTab & saleVol(i, j + 3) & vbTab & saleVol(i, j + 4) & vbTab & saleVol(i, j + 5)
Next i
End Sub