Form 3 Computer Studies Booklet 2
Form 3 Computer Studies Booklet 2
Introduction
A computer follows a set of well-designed instructions (known as a program) to process any type of data.
In computer programming, a program design is known as an algorithm.
The process of designing a program is referred to as algorithm design.
In this topic, the focus will be on
o Introducing fundamentals of computer programming
o Use of algorithm design tool to demonstrate mathematical operations and logical flow of
instructions in a program
o Using Microsoft Visual Basic to demonstrate how to implement an algorithm into a computer.
Terms used in Computer Programming
The following are fundamental concepts used in computer programming
o Computer program
o Programming language
o Computer programming
o Source code
o Object code
o Assembler
o Interpreter/translator
o Compiler
Computer program
Refers to a set of instructions written using a programming language to instruct a computer to perform a
task.
A computer program is a sequence of instructions written using a Computer Programming Language to
perform a specified task by the computer.
It contains a list of variables and instructions that instructs a computer what to do with the variables
Programming languages
This is a formal language that specifies the syntax and semantic rules for writing computer programs.
Examples of programming languages include:-
o BASIC
o C
o C++
o Java
o Pascal
o FORTRAN and
o COBOL
Computer programming
This is a process of writing a computer program using a programming language.
A person who writes programs is referred to as a programmer (software developer, software engineer)
Source code
Refers to a set of instructions written by a programmer that are not yet converted into machine-readable
form.
It is a text file written using programming languages like
o BASIC
o Pascal
o C
o C++
FORM 3 COMPUTER STUDIES STUDY NOTES |
1
Object code
A code formed by converting a source code into a machine readable form.
To convert source code language processors are used.
Examples of language processors include:-
o Assemblers
o Interpreters
o compilers
Assembler
This converts assembly language program into machine readable form that a computer can understand and
execute.
Interpreter
This converts the source code into a machine code statement-by-statement allowing the CPU execute one
line at a time.
The interpreted line is not stored in the computer memory.
i.e. every time the program is needed for execution
o Each line has to be interpreted.
This method was common in the past since computers did not have enough memory to store the object
code.
Compiler
This converts the entire source code into object code.
The object code can be made into an executable file by carrying out another process called linking
o Linking combines the object code with library files that are requested for the execution of the program.
o An executable file (application file) is generated after the linking process.
Low-level languages
Classified as low because they can easily be understood by the computer since they require minimal
effort to convert into computer object code.
They are hardware-oriented hence they are not portable i.e. a program written for one computer
cannot be installed on another computer.
Languages in which instructions are written using binary code. Given that ,
Many lines of code are needed to accomplish even a simple task (like adding two numbers) since data
and instructions are in binary form.
A program written in machine language might look like one shown in Figure below:
From the above code it is hard for a person to understand what the program is all about unless
they have knowledge in machine level programming.
Furthermore, different CPU‟s understand different machine languages
o e.g. the code for the Intel Pentium processors may be differ from Motorola processors.
Therefore, before writing machine code, a programmer has to know for which CPU the program is
written.
Such programs are hard to write and debug from the programmer‟s point of view, but very easy to
execute from the computer‟s perspective.
Were developed in order to overcome the difficulties of understanding and using of machine
languages.
They represented the first successful attempt to make computer languages readable.
They allowed programmers to write programs as a set of symbolic operation codes called mnemonics.
Mnemonics are basically shortened two or three letter words.
A program written in assembly language may look like one shown in Fig. below
Pascal:
Pascal was initially developed as a procedural language to help in the teaching and learning of
structured programming.
FORTRAN: (FORmular TRANslator):
This language was developed for mathematicians, scientists and engineers.
It enables writing programs that solve scientific, mathematics and engineering problems.
COBOL: (Common Business –Oriented Languages): COBOL language is designed for developing
programs that solve business problems such as computer-inventory control systems.
C:
This is a programming language used for developing system software such as the operating
systems.
Ada:
This language was named after the first lady programmer, Ada Lovelace.
It is suitable for developing military, industrial and real-time systems.
Line 2:
The second line is as the program header.
A Pascal program must start with the keyword “program” followed by the name of the program,
i.e. HelloWorld.
The word output in the parenthesis is known as parameter and indicates that the program displays
the output on the screen.
Line 3:
The keyword Begin in the third denotes the start of the executable statements.
This is where the structure of the program is defined using input, processing and output statements.
Line 4:
Writeln(‘Hello World’) is the most important statement in this program.
Once the program is executed, writeln is a Pascal output function for instructing the computer to
display Hello World! on the screen.
Note the word Writeln is a short form of write line.
In programming, write means output while read means input.
Therefore a statement that takes inputs in Pascal uses Readln(value).
Line 5:
The last statement “End.” marks the end of the program.
Once the computer encounters the End (with period), the program is terminated and unloaded from
main memory.
Examples of 4GLs
iv. Progress 4GL,
i. Power Builder,
v. Microsoft Visual Basic and
ii. FoxPro,
vi. Delphi Pascal.
iii. Python,
Line 1:
The first line starting with apostrophe denotes a comment in Visual Basic that explains the
purpose of the program.
Line 2:
The module header is equivalent to program header in Pascal.
However, in Visual Basic, an application may consist of many modules of which Hello World is
one.
Each module must be accompanied by unique name.
Line 3:
Sub Main is known as the Main method or subroutine hence the head sub before Main ( ).
It marks the start or entry point to executable statements.
The first line starting with apostrophe denotes a comment in Visual Basic.
Line 6:
End Sub marks the end of main method.
Once user presses any key and the End Sub and End Module are encountered , the program returns
the control to the operating system to unload the program from memory.
Object-oriented Programming
Currently, there is a paradigm shift from procedural programming championed in 1970s using 3GLs
to Object-Oriented programming (OOP).
In OOP, a program may consist of several objects that interact by sending messages to each.
This is similar to the a person considered as an object sends a message to another person
requesting for something to done.
It is important to point out that, OOP is not classified as a separate generation because it is a shift
in program development methodology.
Most of the programming languages that supported structured programming like C have been
enhanced to support object oriented programming.
In OOP, several objects are linked together through a method known as association to create a
complete program.
i. JavaScript,
ii. VBScript and
iii. Hypertext preprocessor (PHP).
A script is a small program code written in a scripting language and then appended into the HTNL program to add
functionalities like sliding calendar and form validation.
Most HTML elements have an opening and closing tag.
An opening tag is enclosed between<> while a closing one between</>.
The content to be displayed on the browser is enclosed between an opening and closing tags.
For example, the statement <h2> Hello World </h2> will display the word “Hello World” in big bold test on the screen.
Table below shows examples of HTML tags and their meanings:
The guidelines outlined above may be summarised into five main phases of program development life-cycle (PDLC):
i. problem definition.
ii. algorithm design.
iii. program coding.
iv. program testing and debugging.
v. program review and maintenance.
Problem definition
This refers to one‟s ability to identify a problem that needs to be solved using a computer program.
Computer programming is a problem solving task.
A creative programmer identifies problems and opportunities in the society and seeks to provide a computer-based solution.
For example, think of the person who after seeing the tedious task of typing using a manual typewriter decided to develop a
word processing program.
The following three situations may motivate a programmer to develop a computer program:
o Problems or undesirable situations that prevent an individual or organisation from achieving their objects.
o Opportunity to improve the current systems or delivery of services. It can be argued that any unexploited opportunity is a problem.
o New directive given by the management or government requiring change in the status quo.
Sample problem
Consider a mathematical problem such as calculating the area of a circle.
The problem here is to find the area of a circle.
It is the responsibility of the programmer to develop a program that can be used to calculate the area of any circle.
For such a problem, a programmer must conceptualise the solution by first understanding the problem, then identify input,
processing logic and expected output.
A careful analysis of the problem reveals that the process of solving the problem is as follows:
The problem definition stage ends with documenting hardware and software requirements necessary for solving the problem.
It is this document that enables a programmer to design algorithm for implementing the solution.
Algorithm design
After the programmer analyses the problem, the next step is to design the solution to the problem known as algorithm.
An algorithm is a set of well defined steps for performing a task or solving a problem.
The solution is expressed using flowcharts, pseudocode or structural English statements.
For example, to calculate area of a circle, a programmer may use pseudocode to outline the steps followed by a computer
program to calculate the area as shown in Figure below.
Before coding, an algorithm should be tested for logical error, a technique known as '' dry run ''
Sample Pseudocode
The algorithm above start with a declaration on the task to be performed by the program.
The statement SET indicates that 3.142 is a constant represented using a symbolic name PI.
The phrases within the BEGIN and END denotes the executable statements for input, i.e., PRINT radius; process (area = PI *
radius); and output, i.e., PRINT area.
Program coding
Programs can be written in different programming languages but the general trend today is to use high-level languages that are
easy to learn and understand.
For a computer to execute instructions outlined in the algorithm, the statements must be written using a programming
language such as Pascal, C, C++ or Java.
To be executed, the source code must first be converted into object (binary) code.
Generally, most high-level programming languages have common features such as reserved word, operators, identifiers and
variables.
The following sub section highlights some of the elements common in most programming languages.
Reserved words
Reserved word also referred to as keywords have special meaning and can only be used for intended purpose.
Some examples of reserved words in Pascal and C++ include; For, if, else, while and do.
Identifiers
Identifiers are programmer defined symbolic names used to identify elements like variables and constants in a program.
For example, in a program to calculate hourly pay; hours and rate are examples of identifiers.
Operators
Operators are used to perform arithmetic operations on pieces on unary or binary operands.
Five commonly used operators are addition (+), subtraction (-), multiplication(x), division (/) and assignment (=).
For example, a statement to calculate hourly pay can be expressed as:
Wage = hours * rate;
Variables
In programming, a variable is a named location in computer's memory for holding data.
The content of a variable may change during program execution unlike constants whose content doesn't change.
For example, in the previous program for calculating hourly pay; wage, hours and rate are variables.
The sample codes below shows Pascal and C++ programs for calculating area of a circle.
2. Debugging:
Once a program is written in the program editor, the programmer uses debugging utilises to detect and correct syntax errors
before compiling the source code into object code.
1. Simplicity:
A program should be kept as simple and easy to understand.
2. Integrity:
In programming, integrity refers to reliability and accuracy of data.
Therefore, mathematical statements should tested for accuracy of calculated output.
3. Efficiency:
To enhance performance, good program design should aim at optimizing execution speed and memory utilization.
4. Clarity:
For program to be readable, the statements and comments should be clearly written.
5. Modularity:
Complex programs should be broken down into components known as modules, procedures or sub-programs.
iii. It has objects called forms that have a title bar at the top.
The programmer cad the controls such as menu bar, status bar, toolbars, buttons and slide bars onto the form when creating an
application.
iv. It is an object-oriented programming language implemented using a framework known as .NET.
This means that applications developed in VB. Net can also run on internet.
Class
A class is a template or collection of behaviour (methods) and state (variables) that defines a set of objects.
Example
Let's consider the “Form 3”
We can define a template called “exam” with columns student name, marks and grade in which we can add or delete student's
details.
Such a blank template represents the concept “class” in object oriented programming.
Object
An object is an instance of a class that has state (data) and behaviour functions.
Example
A particular student in Form 3 an object who has state or data such as surname, marks and grade.
The student object also has behaviour or functions such as walking; eating that is not in plants class.
Method
This defines the behaviour or function to be performed by an object to manipulate data (state).
Example
We can define a method to add, delete or modify student details in a class.
The class must define methods that are common to all the objects that belong to that class.
Therefore, it is in methods where the program statements that manipulate data are written.
Comments
These are set of statements used in the code to explain what a program or statement does.
Comments are ignored by the compiler during execution.
In Visual Basic, a statement starts with a single apostrophe (') followed by the statement.
Example
Structure of VB Program
Getting started with VB.Net 2010 Express
Visual Basic.Net can be started from the Programs menu by pointing to Microsoft Visual Basic 2010 Express.
Depending on the way the application has been setup, the New Project window is seen as shown in figure below:
i. On the Start page window, click the New Project icon on the top left-hand side to display several types of projects identified
by different icons as shown in figure below:
Forms
A Visual Basic form is an on object on which you insert other objects such as text boxes and command buttons.
Because Visual Basic is an Object Oriented programming language, a form is an object that has state (properties) and behaviour
(methods).
Properties define the appearance of the form object while methods are actions that can be set to execute once you click the
mouse button.
For example, show method makes a form visible on the screen.
Toolbox
The toolbox shown on the right of the form has most of the tools required for programmers to create the application. In fact,
this is the most widely used tools in application development hence we have re-illustrated in fig below.
Toolbox
Listed below are tools that used to create a program by placing their controls on the form.
In object-oriented programming, a control is an instance of an object that appears on the form.
For example, Save button is an instance of command button.
i. Button
This tool is used to place command button instances on the form. Such buttons include OK, Save, Exit, Close etc.
These are the buttons used to interact with an application.
ii. CheckBox
When used on a form, the check box control provides a way of choosing from multiple values by clicking on check boxes.
iii. ComboBox
A combo box is a type of list box that combines the capabilities of a text box and a list box input.
A combobox displays a list of items to select from during program execution.
Items can also be added into the combo box.
iv. DateTimePicker
This tool is used to place a control on the form than the user can click to display a dropdown calendar from which to choose
current day, month or year.
v. HScrollBar
This tool is used to place a horizontal scroll bar such as the one you use at the bottom of most applications to scroll left and
right.
vii. ListBox
The listbox tool is used to draw controls that display list of items the user can select from.
For example, in Windows, you often see a small arrow pointing down which when clicked displays a list you can scroll to
select an item.
ix. TextBox
This is one of those frequently used tools to draw text boxes in which the user provides input.
Text and labels are used hand-in-hand to guide the user on what to enter as input.
Solution Explorer
The solution explorer shown on the top right of the IDE window displays a list of objects associated with the open project such
as forms and modules.
Properties
The properties window shown in fig below is used to define properties of each object in an application.
After placing an instance of an object, define its properties such as name, colour, caption, etc.
Note that the list of properties depends on the object.
Properties list
For example, the figure above shows the properties for command button named Button1.
Always remember to change the default name and caption to reflect the purpose of the button such as OK, Save, Close, etc.
Notice that once the caption is changed, the change is reflected on the property window.
Code Window
The code window is displayed once an object is double clicked.
For example, the code illustrated here was displayed after double clicking Button1.
This is the environment we write the source code that instructs the program what to do such as display mg Hello World on the
form.
Code window
FORM 3 COMPUTER STUDIES STUDY NOTES |
Activity: Hello World
i. To create the Hello World project shown earlier, proceed as follows:
ii. Start Visual Basic and choose New project on the start window.
A project dialog box is displayed.
iii. From the list of Projects, select Windows Forms Application, and then type the name of the projects as
HelloWorldApplication in the Name box.
iv. Once the name of the project is typed, click the OK button.
A blank form will be displayed.
v. Using the Toolbox, draw a label, text box and a command button on the form as shown in fig below.
If the toolbox is not displayed, click the icon that resembles a cross made of a hammer and spanner on the right-hand of
the standard toolbar.
vi. In the Properties Window, change the form, label, text box and command buttons name and caption properties as shown in
the table below.
Make sure the name properties have no space and starts with a prefix such as frm that denotes the type of object.
For example, the name of the form should be frmHello, the label lblHello, the text box txtHello and the comand
button to cmdOK.
These prefixes are conventions used to identify the type of objects in Visual Basic programming.
A code window
NB: The only code that you are required to type in between the Private Sub and End Sub is the following:
Greetings displayed
Startup form
Common, declaration and executable statements
Comments
These are a set of statement included in the code to explain the purpose of the program or statements to the other
programmers or reference in case of future modification program.
In Visual Basic, comments are not executed when the program is run.
A comment must start with an aprostrophe (') followed by the comment statement.
e.g. the following is comment to indicate the statement Hello World is displayed in the text box:
txtHello.Text'display Hello World in the textbox on the form
Declaration
This is an instruction to the compiler to reserve memory enough to store input or output from a computer program.
For a computer to reserve enough memory, the type of data to be held in specific memory address must be specified.
FORM 3 COMPUTER STUDIES STUDY NOTES |
21
Variables
This is a name or identifier that is used to represent a memory location whose content may change during program execution.
When a variable is declared, the computer sets aside memory space to hold a value in the variable.
Variants
In visual basic if a variable type is not explicitly declared, the compiler uses variant data type.
A variant is a special type used if the programmer does not declare a variable data type to be integer, string or the other
types discussed above.
In this case, the actual data type is determined by the value held by the variable.
These types of variables are called variant-type because their data type keeps on changing depending on the values they
hold by the variable.
Although this may not be a good programming practice, use of variant is important where the type of data to be processed
is not known until runtime; i.e. during the program execution.
Constants
A constant is a value that does not change during execution of a program. E.g PI(3.14)
In VB the key word const that comes before PI is used to declare the value as a constant.
e.g. const PI As Double=22/7, means that PI is a symbolic name that holds quotation of 22/7 which is of the type double.
Generally, constants can be classified into three types: string, numeric and named constants.
String constants
A string is a sequence of characters enclosed in double quotation marks.
Strings are used to write alphanumeric values that cannot be manipulated mathematically such as phone numbers,
addresses and names.
FORM 3 COMPUTER STUDIES STUDY NOTES |
The following are examples of strings:
Numeric constants
Numbers that can be manipulated mathematically are referred to as numeric constants.
Numeric constants do not include letters and should not be enclosed in quotation marks.
They can only be of integer, double or scientific type as shown in the following
Examples:
0 3 6000 +70 1.4E+2 1.674 -0.70456
Named constants
A named constant is a value given a symbolic name rather than its actual value.
For example, PI is a named constant used to represent the quotient of 22/7.
Like in variables, if the constant type declaration is ignored, Visual Basic uses variant to determine the data type.
Solution
1. Start Visual Basic and choose New project on the Start Page. Alternatively, add a new form onto an existing project.
2. From the textbox, use the label, textbox and button tools to design the form.
3. Change the name and text (caption) properties of the controls as shown in Table below
Scope refers to the portion of the program that a variable or a constant is accessible by the program.
The following terms are used to specify the scope of a variable or constant:
In the first declaration, the private variable X can only be accessed in the module within which it is declared.
In the second example, the variable Y is public hence it can be accessed by other methods or modules in the application.
Sometimes, a programmer may want to have a single variable that can store several variables of the same or different data
types. Such data type made up of multiple variables components are referred to as user-defined data types. Some examples of
user defined data types are records, arrays, enumerated types and lists. Each
Element or member of a user-defined type can be accessed using a period between the variable name of the user-defined
type and specific member of the type.
For example, if a record known as schoolrecord has a member identified as name to access a value in the name, awe use
schoolrecord.name in the code.
Arithmetic operators
Arithmetic operators are special symbols that are used to write arithmetic expressions like addition, subtraction, division
and multiplication.
It is also possible to carry out other mathematical operations using other operators.
Table below shows a summary of symbols used in arithmetic operations:
NB: The last two rows in the table can be explained as follows:
1. In an integer division using Q operator, each of the numbers being divided is first rounded to become an integer then the
quotation is truncated to an integer.
For example, 2.4\3.5 will result in 2\4 being evaluated.
2. The MOD operator returns the remainder of an integer division. For example, 4 MOD 3 returns 1 and 5MOD3 returns
2.
Example
Write a program that prompts a user to enter two numbers a and b, calculates and then display sum and average of the
two numbers.
Solution
i. Start Visual Basic and choose New project on the Start up Window. Alternatively, add a new form in to an existing
project.
ii. On the toolbox, use a new Label, Textbox and button tools to design the form.
iii. Change the name and text properties of the controls appropriately to identify the two numbers, sum and average.
3. Once calculate the command button is double clicked, enter the code between Private Sub that calculates and displays
sum and average and displays sum and average of the two numbers.
4. If the program is run, the form such as shown in Figure below is displayed
Relation operators
A relation operator is used in an expression that returns a true or false value when evaluated.
The operators can compare numeric variables, constants or expression.
Table below shows a summary of relational operators used in Visual Basic.
Operator Name
= Equal to
<> Not equal to
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
i. Y<>100
ii. y>60
iii. S<=(G+V)
iv. Loss=(Expenses-Profit)
The expression in 1 above will evaluate to true if y is not equal to 100 otherwise it evaluates to false.
A selection statement in a program based on a relational expression would execute depending on the outcome of the
evaluation.
Logical operators
Logical operators are special form of relational expressions to form compound expressions that are true or false.
Table below summarises four types of logical operators used in Visual Basic.
Operator Operation
And Result in a condition that is true if both expressions are true.
Or Result in a condition that is true if one of the conditions is true or both are true.
Xor Result in a condition that is true if one of the conditions is true and the other is
false.
Not Negates the value of a logical expression.
The following are examples of compound expression that demonstrates use of logical operators:
i. (x=30) And (student=”John”):returns true only if value of x=30 and student name is John
ii. (x=20) And (y=30):returns true only if value of x=20 and y is 30
iii. (x=20) Or (y<10):returns true if x is 20 and the value of y is less than 10.
i. P=0.25
ii. E=M*Cˆ
iii. Area=1/2*base*height
iv. X=X+1
NB: The last statement on the right(X=X+1) does not make mathematical sense but this is the beauty of the assignment
statement in programming.
The statement can be interpreted as: Add 1 to the original value of X and then assign the new value to.
In other words, increment the value of X by 1.
Solution
1. Start Visual Basic and chose New project on the Start Page. Alternatively, add a new form in an existing project.
2. Use the Label, Textbox and button tools on the tool box to design the form.
3. Change the name and text properties of the form, labels, text boxes and command button appropriately.
4. Click Calculate Area button, and then write the following code that computes and displays area of a right angled triangle.
Private Sub cmdCalculatedArea Click..........cmdCalculateArea. Click Dim Base, Height As Integer`declare 2 input variables
Dim Area As Double `declare Area as double
Base=Val(txtHeight. Text)
Height=Val(txtHeight. Text)
Area=1/2*Base* Height `calculate area
`display the area of triangle
txtArea. Text =Str(Area)
End Sub
5. Once the programme is run, enter a value for base length and height and then click the Calculate button.
The results of calculation like the one shown in the Figure below are displayed on the form.
Library functions also known as in built functions are methods that have been pre-defined and included in Visual Base.
A Library function performs a task such as calculating a mathematical expression and returns a single value.
A function will usually have a name that can be called when needed to perform a particular task.
A Library function is accessed by its name followed the information that must be supplied to the function enclosed in
parenthesis.
This process is called calling a function.
The variables held in the parenthesis are called arguments.
When the function is called, it uses the arguments to perform an operation and return a value.
For example, to perform a mathematical operation, VB has library function that stars with Math, followed by the function
name after the period e.g. Math.Sqrt(). Table below shows a summary of common Math functions.
NB: The dollar sign ($) may be used with the format function depending on the type of output required.
In the last row of table above, the formatted output is displayed on a label.
5. Once the program is run, the form such as shown in Figure below is displayed.
Note that if the program tries to find square root of a negative value, the program displays NaN.
This means Not a Numeral which in mathematics means; it is impossible.
Such requires operation validation using control structure known section discussed later.
Control Structures
Control structures are constructs that determine the logical flow of execution of program statements.
Sequence
In sequence control structures, the computer reads instructions from a program file starting from the first statement
sequentially moving down to the last statement.
Sample programs illustrated earlier in this unit are sequential program.
Figure below shows how such programs execute statements one after another.
Most programs that solve real word problems give a computer ability to make a decision or execute statement(s) until a
certain condition is satisfied.
In programming, making decision is referred to as selection while repeated execution of statements is referred to as
iteration or looping.
Selection
Situations arise in which a program needs to carry out a logical test, and then take a particular action depending on the
outcome of a Boolean test.
A Boolean test is an expression that uses relational operators like
i. (=(equal to),
ii. >(greater than),
iii. <=(less than),
iv. >=(greater than or equal to) and
v. <=(less than or equal to)
or logical operators like (AND, OR and NOT) to return true or false.
For example, consider a program to test if x is greater than 20 (x>20).
In such a case, if a user enters a value of x, it is compared against 20 and the program returns true or false depending on
the outcome.
This is known as conditional evaluation where the output is a boolean value true or false.
Generally, there four types of selection statements used in Visual Basic programming.
1. IF... THEN
2. IF... ELSE
3. Nested IF.
4. Select... case.
IF selection
IF... THEN selection evaluates the statement within the selection body if the boolean value returned is true.
In this case, if the boolean value is false, the statements are ignored.
For example, in a school, the administration may decide to reward only those students who attain a mean mark of 80%
and above.
If a student scored 80% and above, he or she is rewarded while the rest are ignored. The general structure of IF... THEN
selection is:
IF <condition> THEN
<statements if true>
END IF
Solution
The following is a sample VB. N et program that implements the IF selection to determine whether to display Pass.
Note that the dashes indicate omitted arguments.
Once the program is run, the form such as shown in Figure below is displayed.
Note that when a score below 50 is entered, nothing is displayed in the Remarks textbox.
If selection
IF...ELSE Selection
IF...ELSE selection is suitable when there are two alternatives to choose from.
For example, in a football match, if a player does a mistake which is considered serious by the rules of the game, he/she is
given a red card.
Otherwise, he/she is given a yellow card.
The general structure of IF...ELSE selection is:
If…Selection
Nested IF Selection
Nested IF or the IF..ELSE…IF selection is used where two or more options have to be considered to make a selection.
The general structure of IF…THEN..ELSE selection is:
IF<condition>THEN
<statements>
ELSE IF<condition>THEN
<statements>
ELSE IF<condition> THEN
<statements>
ELSE<condition>THEN
END IF
Once the program is run, the form such as shown in Figure below is displayed.
The gross salary of Chifira Bookshop is based on the basic salary and additional benefit as follows”
a) Employees who have worked for the company for more than 10 years receive additional of 5% to their basic
salary.
b) Monthly salary bonus based on monthly sales of books as follows:
Do WHILE....LOOP
Explanation
1. The condition balance > 0 is first tested.
2. If it is true, the account holder is allowed to withdraw cash.
3. The program exits the loop only when the balance falls to zero.
Solution
1. Start Visual Basic and choose New project on the Start Page. Alternatively, add a new form in existing project.
2. From the toolbox, use the Label, Textbox and button tools to design the form.
3. Change the name and text properties of the textboxes and command button.
4. Double click the button and insert the code below in the Private Sub section.
Private Sub cmdCount_ Click (…...) Handle cmdCount. Click
Dim number As Integer
Dim sum As Integer
Dim Average As Double
number = 0 ´assign initial value as 0
sum =0 ´initial value of sum is 0
Do While number < 10 ´test if true
sum = sum + number
number = number + 1
txtCount. Text = Str(number)
Loop ´end of loop tested here
Average = sum/number
´display count, sum and average
txtSum.Text = Str(sum)
txt Avereage. Text = Str(Average)
End Sub
5. Once the program is run, the form such as shown in Figure below is displayed.
Do While Loop
In the previous problem of calculating the sum and average of 10 number, we can replace Do While...Loop with
While.. Wend as follows:
Do Until... Loop
Like the Do While and While... Wend loops that executes the statements if the condition is true. Do Until..Loop
executes the statement in the body of loop if the condition is true.
For example, the sample program on counting numbers can be rewritten as follows:
Practical Activity
1. Rewrite the program for counting the first ten numbers, and then displays their sum and average using
While...Wend.
2. Rewrite the program for counting the first ten numbers, and then displays their sum and average using the Do
Until...Loop construct.
Do
Withdraw cash
Update balance
UNTIL balance ≤0;
The general syntax of the Do...Loop While loop supported by Visual Basic is:
DO
<statements>
Loop While <condition>
Using the Do.. Loop While control structure, write a program that displays total count of the first ten numbers
(0,2, ...9), their sum and average in separate text boxes.
Solution
1. Start Visual Basic and choose New project on the Start Page.
Alternatively, add a new form in to an existing project.
2. From the toolbox, use the Label, Textbox and button tools to design the form.
3. Change the name and text properties of the textboxes and command button.
4. Double click the count button and then insert the code below in the Private Sub section.
5. Once the program is run, the form such as shown in Figure below in worked is displayed.
Do While Loop
For.. Next loop
For.. Next is an alternative to while loop used in case the number of repetitions are known.
For example, to calculate the sum of 10 numbers, the For..Next loop is appropriate because the number of looping
is predefined as 10.
The loop executes the statements within the loop ten times before the total sum is displayed. The general format of
the
FORM 3 COMPUTER STUDIES STUDY NOTES |
39
For..Next loop is:
For index = lowerlimit To upperlimit STEP<index>
<statements>
Next index
Note that the STEP part controls the looping such that you can count in increments of 1,2,3 etc,
For example, to set count to even counts starting from zero, use the following STEP index: