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

_Programming_A_level_comp_science

The document provides an overview of programming languages, categorizing them into low-level (machine and assembly languages) and high-level languages (imperative, object-oriented, and declarative). It discusses the characteristics, advantages, and examples of various programming languages, including their applications in different fields. Additionally, it explains concepts such as constants, variables, expressions, and identifiers in programming.

Uploaded by

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

_Programming_A_level_comp_science

The document provides an overview of programming languages, categorizing them into low-level (machine and assembly languages) and high-level languages (imperative, object-oriented, and declarative). It discusses the characteristics, advantages, and examples of various programming languages, including their applications in different fields. Additionally, it explains concepts such as constants, variables, expressions, and identifiers in programming.

Uploaded by

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

1

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.

Low level languages (LLL)


Machine Language-1st Generation
 The 1st generation of computer language is machine language (late 1940s).
 It is the actual patterns of 0s and 1s used in the computer memory.
 The programming of Colossus and other early computers was laboriously done with
toggle switches representing a pattern of binary codes for each instruction.
 It was difficult to write and led to many errors in program code that were difficult to
debug.
Assembly code-2nd Generation
 Early 1950s, the 2nd generation was introduced i.e. Assembly language.
 It is written in using mnemonics (abbreviations that represent the instructions in more
memorable way).
 Assembly language is translated into machine code using a program called assembler.
 Each assembly language instruction is translated into equivalent machine code statement.
 Assembly language and machine code are called low level languages.
 Assembly language and machine code are machine dependent i.e. each type of
computer will have its own assembly language.

Advantages of Assembly code


 Assembly language occupy as little space as possible and execute as fast as possible.
 Assembly language are still used for applications where timing or storage space is critical,
e.g. parts of operating system and device drivers programs in embedded system.

Part of an Assembly code program

LOAD A, #0 \Load register A with 0


LOAD X, #8 \Load index register with 8
LOOP SUB X, #1 \Subtract 1 from index register
STORE X, (&50000),A \Store contents of A in location 5000 indexed
\by contents of X
BNE X, LOOP \Branch if not zero to LOOP
HALT \Stop execution

High level languages (HLL)


Imperative high level languages-The Third Genearation
 As thecomputer use increased dramatically in (late 1950s – 1970s) ,the need grew to
make it easier and faster to write error-free programs.
 HLL are designed around the problem to be solved rather than the machine .
Characteristics of HLL

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
2

 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

Procedural (Imperative) languages


 They specify how to solve a problem as a sequence of steps. E.g. To find the area of a
rectangle the steps are:
1. INPUT the length
2. INPUT the breadth
3. Multiply the length by the breadth and store the result
4. OUTPUT the result.
 Each line of code is executed one after the other in sequence.
 They use the constructs: sequence, selection and iteration
 The programmer has to specify exactly what the program has to do.
 Procedural languages are used to solve a wide variety of problems e.g. to solve scientific
and engineering problems (FORTRAN and ALGOL), while others are more suitable for
solving business problems(COBOL) and others are suitable for solving control problems
that need real time solutions e.g. C, Ada, Modula-2 and Occam
 Procedural languages may include functions and procedures but they always specify the
order in which instructions must be used to solve the problems.

Features which make FORTRAN suitable for mathematical applications


 It has large library of inbuilt mathematical functions such as log, sqrt, sin etc.
 Comprehensive libraries of statistical and engineering routines are readily available and
well documented.
 Double precision arithmetic means that calculations can be performed with great accuracy
 Good array handling capabilities means suitable for solving e.g. large sets simultaneous
equations.

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
3

Facilities which make COBOL a suitable for data processing applications


 Good validation facilities
 A sort verb which allows files to be sorted into any sequence
 Excellent file handling capabilities
 Good report formatting capabilities
 Facility to access database from within a COBOL program

Problems in maintaining programs written procedural language


 If the structure of the data changes all programs which use the data need to be altered e.g.
the addition of a new field may cause changes to a number of programs in a system.
 If the functions of the system changes, program alterations will be widespread. e.g. if a
bank change cheque processing from batch to an interactive process, it leads to a totally
redesigned system even though actual data entities don’t change.

Object –oriented programming language (Visual Basic)


An object-oriented program implements objects that contain both the data to represent these
objects and the operations/methods that can be performed on them.
 Data and operations are encapsulated that is they are combined together.
 Data encapsulation is the concept that data can only be accessed via the methods provided
by the class.
 A class is a description of an object. E.g. Bank Account

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:

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
4

 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 and procedure for a button object

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

HUMAN CLASS TIGER CLASS


(Inherits these properties and methods)
(Inherits these properties and methods)
Properties Methods
Age Eat Properties Methods
Gender Breathe Age Eat
Body Temperature Sleep Gender Breathe
Body Temperature Sleep
Additional Properties and Methods Additional Properties and Methods
Name Talk
Species Hunt
Address
Fur colour

TEACHER CLASS STUDENT CLASS

(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

Additional Properties and Methods Additional Properties and Methods


Name Talk Name Talk
Address Address

Additional Properties and Methods Additional Properties and Methods


Employee Number Teach Year Study
salary Exam results

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
5

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.

Example of Prolog database


/* fact */
1. parent (jim, joan).
2. parent (mark, linda).
3. parent (sarah, joan).
4. parent (jim, Kevin).
5. parent (sarah, Kevin).
6. female (joan).
7. female (linda).
8. female (sarah).
9. male (mark).
10. male (Kevin).
/* rule*/
11. Father (A, B), /* A is the Father of B if */
parent (A, B), /* A is a parent of B and */
male (A) . /* A is Female */
Father (A, B) IF parent (A, B) AND Male (A)
12. Mother (A, B) IF parent (A, B) AND female (A)

NB
 Clause 1 to 10 are facts
 Clause 11 and 12 are rules
 A capital letter denote a variable.

*Prolog operates by attempting to satisfy a series of goals /query.

a) A query might be mother (sarah, joan)


Use rule 12 by looking for parent(sarah, joan)
Having found this in fact 3, satisfy the goal female(sarah)
Having found in fact 8, the answer is yes.

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
6

b) Another query might be mother (X, joan)


Use rule 12 to satisfy this goal
Satisfy the subgoal parent (X, joan)
Parent (jim, joan) is found in fact 1
Satisfy female (jim)
The goal is not satisfied
Backtrack to subgoal parent(X, joan)and continue down the database, parent(sarah) is
found on fact 3
Satisfy subgoal female(sarah)
The goal is satisfied in fact 8
Therefore X = sarah.

General purpose languages


 Are developed to solve different problems
 Example of general purpose language is Pascal

Special purpose languages


 Are developed to solve specific problems
 Examples are: COBOL, C etc

7.5.3 Programming Languages

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
7

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()

VB.NET windows interface program

Area Of Circle

Enter Radius

CLICK TO SHOW ANSWER

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
8

Public Class Form1


Dim area,radius as single
Const pi as single=3.14159

Private Sub button1.click( )


.radius=textbox1.text

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( )

Dim area,radius as single


Const pi as single
pi.=3.14

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()

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
9

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
10

Msgbox(count)
Loop

Selection If Number>0 then


Number=Number +1
Else
Number = Number – 1
EndIf

Select case number


Case is >0
Number=Number + 1
Case Else
Number=Number -1
End Select

Procedural Calls Adjust(NoOfSpaces,NoOfStars)


Function Calls FirstLetter=Initial(Surname)
Call Initial(Surname)
Totalling Total=total + Number
Decrement X=x-1
Increament X= x +1

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.

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
11

Selection constructs – They perform a logical test to determine the course of


action to be taken. Therefore depending on situations, different paths may be
followed.
Iteration construct – iteration is a vital task that a computer does. Loops depend
on a logical test like in selection construct, however the statement or statements
may be executed several times.
5) Block structure
 Programming languages that encourage the use of blocks are called block structured
languages.
 A block is a group of program statements that are treated as a single unit
 A block consists of a declaration part, which includes constant, variables and type
definitions and procedures and function declarations and a statement part.
 VB,net blocks includes Module---End Module,Sub----End Sub

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

Dim area,radius as single


Const pi as single
pi.=3.14

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
12

 A relational operator is used to separate a condition and its value or text.


Operator Meaning
= Equal to
> Greater than
< Smaller than
>= Greater or equal to
<= Smaller or equal to
<> Not equal to

Simple Selection
Syntax IF condition THEN
Statement
Endif

Example If average > 40 Then


Print “Passed”
Endif
Worked example
Question
Write a program that will input two numbers. If the first number is greater than the second number, then print the word
‘greater’.

Answer
Rem Declare Variables

Dim First As Integer


Dim Second As Integer

Private Sub Form_Load( )

Rem Input numbers

First = InputBox ( “ enter a number” )


Second InputBox ( “ enter another number” )

Rem compare values

If First > Second Then


Form1.Show
Print “greater”
End If

End Sub
Binary Selection - Format 1
Syntax IF condition THEN
Statement(s)
Else
Statement(s)
ENDIF

Example IF average > 40


Print “Passed”
Else
Print “Failed”
ENDIF
Worked example

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
13

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

Dim No_Miles As Integer


Dim Eng_size As Integer
Dim Allow As Integer

Private Sub Form_Load ( )

Rem input values

No_Miles = InputBox ( “ enter miles travelled” )


Eng_size =InputBox ( “ enter size of engine” )

Rem calculate allowance depending on engine size

If Eng_size <=1300 Then


Allow = 10 * No_Miles
Else
Allow = (10 + 5) * No_Miles
End If

Rem print results

MsgBox “Allowance “ & Allow

End Sub

Dry run the program with the following data and write the expected result

Miles Travelled Size of Engine Is Size <= 1330cc Expected Result


100 1 000
100 1 700

Binary Selection - Format 2


Syntax IF condition 1 THEN
Statement(s)
ElseIf condition 2 THEN
Statement(s)
Else
Statement(s)
ENDIF

Example IF Total Cost > 2 000 THEN


Print “Discount allowed”
ElseIf Total Cost = 2 000 THEN
Print “No Discount”

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
14

Print “Your purchase must be greater than 2 000”


Else
Print “No discount”
ENDIF
Condition 1 Condition 2 Result
True True True Note: The Print statements can be used in different
True False False ways:
False False False Form1.Print :Prints the message in Form 1 form
False True False Print :Prints the message on the screen
Print.Print :Moves the cursor to a new
line then prints the message on the screen
Debug.Print :Prints the message in the immediate window
Printer.Print :Prints the message on the printer
Print;Tab(20) :Position the cursor at column 20 then prints the message there

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.

Multiple Selection – Using logical operators OR/AND


When a selection is based on one or more conditions, logical operators are used to separate the
conditions

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

Condition 1 Condition 2 Result


True True True
True False True
False False False
False True True
This indicates that the instruction following This indicates that after THEN will be executed
THEN will only be executed if both conditions if any of the condition is TRUE or both are TRUE

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
15

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

Example Dim grade As String

Private Sub Form_Load ( )


grade = InputBox (“Enter exam grade”)
Select Case UCase (grade)
Case “A”
Print “Excellent!”
Case “B”
Print “Can improve!”
Case “A”
Print “Must be more serious!”

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
16

End Select

End Sub

SELECTION USING CHECK BOX AND OPTION BUTTON

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.

Check Box Properties


Properties Effect
Caption Set the text to display beside the check box
Font Sets the font type
Value Value can be unchecked (0, vbUnchecked), checked, (1, vbChecked), or
grayed out (2, vbGrayed)
Check Box Event
Click Event obtained when you click on the check box at run-time

OPTION (RADIO) BUTTON


An Option Button allows you to select only one item from a list of options.
Option Button Properties
Properties Effect
Caption Set the text to display beside the option button
Font Sets the font type
Value If a button is selected, its value will be True, otherwise False.

Click Event obtained when you click on the option button.

USE OF FRAME WORK


A Frame groups controls in a form.

Properties Effect
Caption Set the text to display beside the check box
Font Sets the font type

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
17

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)

check boxes (1-4)

Command Buttons (1-3)


Set Properties
Form Properties
Use two forms
1st Form
Name :frmMember
Text :Members Information
nd
2 Form
Name :frmOutput
Text :Output

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
18

Text :Meal

NB set properties for Labels 2-5 and Text box 1-4


Radio button properties
Radio button that belong to the same frame have similar names. After giving the first name and
while assigning further ones, Vbasic will prompt you to create a control array. Answer Yes.

Radio button 1 Name :optSx


text :Male
Value :True

Radio button 2 Name :optSx


text :Female

Radio button 3 Name :optSx


Text :Single
Value :True

Radio button 4 Name :optSx


Text :Married

Check Boxes properties


Check boxes that belong to the same frame have similar names. After giving the first name and
while assigning further ones, Vbasic will prompt you to create a control array. Answer Yes.

Check Box 1 Name :chkMeal


Text :Veg

Check Box 2 Name chkMeal


Text :Fish

Check Box 3 Name chkMeal


Text :Chicken

Check Box 4 Name : chkMeal


Text : Meat

NB set properties for Command Buttons (1-3)

CODE THE PROJECT

USE OF CMBO BOX


 Combo allows you to select one item from a list.
 There are two parts in the combo box:
A text box that contains the title

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
19

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.

Combo Box Properties


Properties Effect
Name Sets the name of the combo box
Font Sets the font type
Appearance Sets 3d or flat
List Allows you to give the items in the combo box list. Alternatively you
can use VB ‘With ... End’ with commands to do the same task
Sorted Selects ‘True’ to arrange the items in order, otherwise the items will be
displayed in order given
Style Sets the type of combo box you desire:
0 – dropdown Combo – provides the dropdown list when the
down arrow is selected. You can type an item directly (even if that
item is not in the list) or select an item from the list.
1 – Simple Combo – you are presented with the drop-down list at
all times. You can select an item from the list or type an item, even
if it is not in the list.
2 – Dropdown list – You cannot type an item; you have to select an
item from the list. This style is important when space is an
important element to consider.

Combo Box Event


Click Event obtained when you click or double-click or change the value, or
DbClick position on the combo box.
Change With these methods, you can define the operations to perform
Got focus,etc depending on the choice you have made

Example use of combo box

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
20

Label properties
Label 1
Name :lblUser_name
Caption :&User Name

Label 2
Name :lblPassword
Caption :&Password

Combo Box properties


Name :cboUser_name
Style :0 – Dropdown Combo

Text box properties


Name :txt
Border Style :1 - Fixed Single
PasswordChar :* (this will hide the password by displaying *)

Command Button properties


Command button 1
Name :cmdOk
Caption :&Ok

Command button 2
Name :cmdQuit
Caption :&Quit

Main Form

Form properties Back Style :Transparent


Name :frmMain Border Style :1 – Fixed Single
Border Style :1 – Fixed Single Caption :WELCOME
Caption :Main Font size :24
Startup Position :2 – CenterScreen

Label properties
Name :lblTitle
Alignment :Center

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
21

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

Private Sub cmdOk_Click()


'clicking on the ok button causes the main menu form to be dispalyed
If (cboUser_name.Text = "Administrator" And txtPassword.Text = "roshun") _
Or (cboUser_name.Text = "nooreen" And txtPassword.Text = "banu") _
Or (cboUser_name.Text = "abdal" And txtPassword.Text = "hassan") Then
'checks for valid password for given user name'
'displays a message if password is incorrect
Me.Hide
frmMain.Show
Else
Beep
MsgBox "Wrong Password entered", vbCritical, "Error"
'message to state that a wrong password has been entered
End If

End Sub

Private Sub cmdQuit_Click()


'clicking the quit button causes the program to terminate
End
End Sub

Coding – Main Form


Private Sub cmdClose_Click()
End
End Sub

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
22

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

Type the following program in view code window


Rem program to print intergers from 1 – 5

Private Sub Form_Load ( )


Frmoutput.Show
For counter = 1 – 5
Print Counter
Next Counter
End Sub

The STEP Clause


The STEP clause is used in For ... Next loops to enable the counter to increase or decrease by a
value which is greater than or less than 1

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

Type the following program in view code window


Rem program to print even numbers less than 20

Compiled byPrivate
ChiseseSub
L Form_Load ( ) 0772 563 672
26 July 2021 Frmeven.Show [email protected]
For counter = 1 – 5
Print Counter
23

Do While ... Loop


Syntax instructions
Initialise counter
Do While condition
Instructions
Increment or decrement counter
Loop
Instructions
NB condition is the number of times you want to execute the program segment.

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

Type the following program in view code window

Rem program to print intergers from 1 – 5

Private Sub Form_Load ( )


FrmList.Show
Counter = 1 – 5
Do While counter < 6
Print Counter
Counter = ounter + 1
Loop
End Sub

Do ... Loop Until


Syntax instructions
Initialise counter
Do While condition
Instructions
Increment or decrement counter
Loop
Instructions
NB condition is the number of times you want to execute the program segment.
Activity

Write a program using Do... Loop Until that will output the integers from 1-5

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
24

Solution
Open a form with the following properties
Name :frmListintegers
Caption : Integers

Type the following program in view code window

Rem program toList intergers from 1 – 5

Private Sub Form_Load ( )


frmListintegers.Show
Counter = 1
Do
Print Counter
Counter = ounter + 1
Loop Until counter > 6
End Sub

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
25

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, Procedure and Functions

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

Sub Adjust(Byval Spaces as Integer,Byval Stars as integer)


Spaces=Spaces-1
Stars=Stars + 2
End Sub

Example

Consider the following problem.The user enters two numbers and the algorithm outputs their
product.

Solution one

Using a structure diagram


Design for an algorithm to output the pro

Product

Get two Multiply Output


Show
the answers
instructions
Compiled by Chisese L numbers 0772 563the
672numbers
26 July 2021 [email protected]
26

Solution 2

Place the following code on calculate product button

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles_


btnCalculate.Click

Dim num1, num2 As Double


Dim product As Double

MsgBox("The purpose of this program is to display two numbers and their_


product",,”Purpose”)

num1 = 5.5
num2 = 4.0

product = num1 * num2


MsgBox("The product of" & FirstNumber & "and" & SecondNumber & "is" & Result,_
"Result")

End Sub

Solution 3
Using procedures

Public Class Form1

1. Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles


2._btnCalculate.Click
3.
4.
5. Dim num1, num2 As Double
6. Dim product As Double
7.

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
27

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

Explanation on the above code


- The ExplainPurposeofProgram( ) is a procedure which displays the purpose dialog.
- The OutputResult( ) procedure displays the result of the calculation.
- Line 8 calls the procedure ExplainPurposofProgram
- The call passes control to line 17 and the instruction at lines 18-19 is executed.
- Line 21 passes control to the instruction immediately after the calling instruction ,that
is, to line 9.
- The instructions on line 10,11 and 13 are now executed.
- The instruction on line 14 calls the procedure OutputResult.
- This looks different from the call on line 8 as the name is followed y three arguments
- The call passes control to line 23 .
- The procedure name is followed by three parametres
- The compiler matches the arguments in line 14 to the parameters in line 23.

Procedure arguments

OutputResult(num1,num2,product) The statement that


calls the procedure

Procedure interface(header)

Sub OutputResult(ByVal FirstName,ByVal SecondNumber,ByVal Result)

Procedure name Procedure parameters

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
28

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

Function Initial(S as String) as String


S=LeftStr(s,1)
Initial = UpperCase(s)
End Function

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
29

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.

There are two common types of array:

1. one-dimensional array
2. two-dimensional array.

One –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.

The format for a one-dimensional array is ArrayName(x).

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
30

Two dimensional array

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) .

Table 16.2 Two Dimensional Array


Name(1,1) Name(1,2) Name(1,3) Name(1,4)
Name(2,1) Name(2,2) Name(2,3) Name(2,4)
Name(3,1) Name(3,2) Name(3,3) Name(3,4)

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:

Dim saleVol(1 To 4, 1 To 6) As Integer

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

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]
31

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

*Note: the keyword vbTab is to create a space


The Output

Compiled by Chisese L 0772 563 672


26 July 2021 [email protected]

You might also like