Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
33 views40 pages

Form 3 Computer Studies Booklet 2

The document provides an overview of programming fundamentals, including definitions of key concepts such as algorithms, programming languages, and the processes of writing and converting source code. It categorizes programming languages into low-level and high-level languages, detailing their characteristics, advantages, and disadvantages. Additionally, it discusses the evolution of programming languages through different generations, including examples of various languages and their applications.

Uploaded by

kansichig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views40 pages

Form 3 Computer Studies Booklet 2

The document provides an overview of programming fundamentals, including definitions of key concepts such as algorithms, programming languages, and the processes of writing and converting source code. It categorizes programming languages into low-level and high-level languages, detailing their characteristics, advantages, and disadvantages. Additionally, it discusses the evolution of programming languages through different generations, including examples of various languages and their applications.

Uploaded by

kansichig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Programming Fundamentals

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.

History of programming languages (HOPL)

 Hundreds of programming languages have been developed over the years.


 These languages are classified into two broad categories:
1. Low-level languages
2. High-level languages
 These categories can be subdivided into five generations.
 The low-level languages consists of first generation and generation languages while the high-level has
third generation to fifth generation languages.

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.

Types of low-level languages


 There are two types of low-level languages: machine languages and assembly languages.

Machine languages (First generation languages)

 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:

FORM 3 COMPUTER STUDIES STUDY NOTES |


 Therefore, before writing machine code, a programmer has to know for which CPU the program is
written.

A Sample Machine Language Program

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

Assembly languages (Second generation languages)

 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

Sample Assembly Language Program


 The first line in the code means move 15 into the processor register with the name AX.
 The second line instructs the computer to subtract 10 from the value in register AX.
 Programs written in assembly languages require an assembly to convert into machine codes that the
computer can understand.
 Like machine languages, assembly languages are also machine dependent and therefore a program written for
one computer cannot be used on another.

Advantages of low-level languages


1. The CPU understands machine language directly with minimal or no conversion.
2. The processor executes low-level programs written in faster because complex instructions are already
broken down into smaller simpler ones.
3. Low-level languages are stable and hardly crash or break down once written.

Disadvantages of low-level languages


1. Low –level languages are difficult and cumbersome to use and learn.
2. Require highly trained programmers both to develop and maintain programs written in low-level languages.
3. Correcting errors (debugging) in low level language programs in difficult.
4. Low level programs are machine dependent i.e. they are not portable from one to another.
FORM 3 COMPUTER STUDIES STUDY NOTES |
3
High-level Languages
 These are close to the human language hence they can be read and understood even by people who are not
experts in programming.
 High level languages are machine independent meaning that a programmer concentrates on problem solving
a particular problem instead of understanding the architecture of the machine.

Types of High-Level Languages


1. Third generation languages. (3 Gls)
2. Fourth generation languages. (4Gls)
3. Fifth generation languages. (5 Gls)
4. Object oriented languages. (OOPs)
5. Web scripting languages.

Third generation languages (3GLs)


 They are also called structured or procedural languages.
 A procedural language makes it possible to break down a program into components called modules,
each performing a particular task.
 The process of breaking down a program into modules or sub-program is referred to as structured
programming.
 Structured programming approach emphasises the following:
1. large programs should be broken into smaller sub programs each performing a single task.
2. use control structures in problem solving.

Benefits of structured programming


i. it is flexible,
ii. Easier to read and
iii. Easier to modify.
 The following is a brief description of common examples of third generation programming
languages.

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.

BASIC:(Beginners All-purpose Symbolic Instructional Code):


 This language was developed to enable students easily learn programming.
 It is a simple general purpose language used for developing business and educational applications.
 It is a powerful tool for student who wish to learn programming because of its simplicity.

C:
 This is a programming language used for developing system software such as the operating
systems.

FORM 3 COMPUTER STUDIES STUDY NOTES |


 It is the one of most popular and powerful high-level programming languages because of its
ability to provide programmers with powerful features of low level languages and at the same
time easily understandable as a high level language.

Ada:
 This language was named after the first lady programmer, Ada Lovelace.
 It is suitable for developing military, industrial and real-time systems.

Sample 3GLs program


 A simple source code known as “Hello World” may be used to introduce beginners into
structured programming as shown in fig below:

Sample helloworld Program in Pascal


Line 1:
 The first line enclosed is a combination parenthesis asterisk is known as comment.
 In programming, comments are used to explain the purpose of a program statement to other
programmers.

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


5
Fourth generation languages (4 GLs)
 4 GLs were improved on 3GLs to reduce programming effort by making the programmer focus
more on the problem than algorithm or structure of the program.
 Note that 4GLs may also be enhanced by 3GLs meaning that the two generations overlap.
 However, unlike 3GLs, most 4GLs have advanced programming tools used for
o integrating programs with database,
o generating reports and
o creating graphical user interface (GUI) applications.
 The programmer may also use application generator that automatically generates program code
hence relieving the programmer from tedious work of writing every line of code.

Examples of 4GLs
iv. Progress 4GL,
i. Power Builder,
v. Microsoft Visual Basic and
ii. FoxPro,
vi. Delphi Pascal.
iii. Python,

Sample 4GLs Program


 The same Hello World program demonstrated using Pascal can be rewritten using a 4th Generation
programming language.
 Figure below is Hello World in Microsoft Visual Basic. Net.

Hello World Program in Microsoft Visual Basic


 This program in Visual Basic 2010 is similar to one demonstrated using Pascal except for syntax
difference.
Brief explanation of the Hello World Program in Microsoft Visual Basic

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


Line 4:
 Console. Writeln(“Hello World”) statement is similar to writeln used in Pascal.
 The term console means screen.
 Therefore, once the program is executed, writeln instructs the computer to display Hello World! on
the screen.
Line 5:
 Console. Readkey() function is similar to readln used in Pascal.
 However, in this program, it is used to pause the screen displaying Hello World until the user
presses any key.

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.

Fifth generation languages (5 GLs)


 5 GLs also known as natural languages are used to develop systems that solve problems using
artificial intelligence.
 Artificial intelligence refers to the computer system that mimic human-like intelligence.
 Such intelligence includes visual (seeing) perception, speech recognition, decision making and movement.
 In 5 GL programming, the programmer only worries about constraints required for the problem to
solved but not designing the problem solving logic referred to as an algorithm.
Examples of 5 GLs
i. PROLOG,
ii. Mercury,
iii. LISP and
iv. OPS5.

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.

Examples of object oriented programming languages


i. Microsoft Visual Basic, v. C++, ix. Ruby,
ii. Java vi. C#, x. Delphi Pascal and
iii. Net, vii. Python, xi. Smalltalk.
iv. Objective-C, viii. Perl,

FORM 3 COMPUTER STUDIES STUDY NOTES |


7
 It is important to point out that, OOP languages cuts across the three generations of high-level programming languages.
 Most of the programming languages that supported structured programming have been enhanced to object oriented
programming.

Sample OOP Program


 Fig below shows a sample Hello World written in GUI environment of Visual Basic.Net.
 The structure of the program is described later in the section on Visual Basic programming in order to appreciate use of classes
and objects.

Web development and scripting language


 Web development language is used to develop or add functionalities on web pages.
 Web pages are hypertext document created in a language called hypertext markup language (HTML).
 HTML consists of tags that are interpreted by the web browser software to display content when the file is opened on the
browser.
 A tag is a word, symbol or character enclosed in angle brackets<>that a browser can interpret it as a command.
 For example, to create HTML document, one must use the <HTML> tag at very top of the document.
 Other languages like Extended HTML (XML) have been derived as alternative to HTML with the only difference being that
XML tags.
 Unlike programming languages, HTML does not have declaration part and control structures (to be covered later in the book).
 This is why it is not considered as programming language.
 To enhance interaction and dynamism of HTML web pages, special types of web programming languages known as scripting
language are used.

Examples of scripting language

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:

FORM 3 COMPUTER STUDIES STUDY NOTES |


8
TAG MEANING
<html></html>  Marks the beginning and end of a HTML document.
 All other tags and text fall between these two tags
<head></head>  Marks the header part of the document.
<title></title>  Gives title of the web page.
 Text between these tags appears in the title bar when the page is browsed.
<body></body>  Marks the content part of the web page
<h1></h1>  Sets size of text with H1 being the largest and H6 being the smallest size

Sample HTML Page


 A simple structure of HTML is demonstrated using figure below for a web page that displays Hello World on a browser.
 Although the code can be written using any text editor, the file must be saved with .html extension for the browser to display
(render) the Hello World on the screen.
 In this example, the browser displays Hello World using Heading1 text size and Greetings in the title bar of the browser.

A hello World Program in HTML


Benefits High-Level Languages
1. High level language are portable i.e. can be installed in more than one computer.
2. High level language is user friendly, and easy to use and learn.
3. High-level language is more flexible.
 It enhances creativity and innovation of the programmer and increase productivity in the workplace.
4. It is easier to correct programs written in high level languages.
Limitations of High-Level Languages
i. Their nature encourages use of many instructions in a statement hence the size of these instructions cause slower program
processing.
ii. High -level language programs have to be interpreted or compiled to machine form before the computer
iii. They require large computer memory to be executed

Program development process


 Quite often like in mathematics, when student are given a programming problem, they have difficulties in analysing and
providing a solution.
 The following are the guidelines on how to solve a programming problem:
i. Clearly define what a program is to do (program definition).
ii. Close your eyes and visualise the program running on the computer.
iii. Write a psuedocode version (algorithm design) of the program.
iv. Desk-check (dry-run) the pseudocode for any logical flow errors.
v. Write the program code on paper using a programming language.
FORM 3 COMPUTER STUDIES STUDY NOTES |
9
vi. Test the program on a paper for any syntax and logical errors.
vii. Write the source code using programming such as Basic or C++.
viii. Compile the program and correct any error displayed by the compiler.
ix. Run the program with test data for input to test for any logic errors.
x. Validate the result of program.

 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:

Input: Pie(π ) which is constant.


The radius of a circle
Process: The formula for calculating area of a circle i.e. π x radius x radius.
Output: Area of a circle (A).

 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 ''

FORM 3 COMPUTER STUDIES STUDY NOTES |


Program: Calculate area of a circle
BEGIN
SET as constant PI = 3.142
PRINT '' Enter Radius''
READ radius
area = PI * radius
PRINT area
END

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


11
Program in Pascal Program in C++
Program Area circle (input, output); # include <iosteam.h>
Const PI = 3.142; double radius, area;
Var radius, Area: real; double pi = 3.142;
main ( ) {
Begin
Writeln ('Enter the radius'); cout << 'Enter the radius';
Readln (radius); cin>>radius;
Area: =Pi * Radius * Radius; area = pi * radius * radius
Writlen ('The area is',Area) cout<<'The area is', area;
End. return 0;
}

 NB: Unlike Pascal, C++ is case senstive.


 This means that read and write functions like can (console in) and cout (console out) should be in lower case.
 Note also that, stars of executable statement in, C++ stars with the main function written in lower case.

Program Testing and debugging

 Testing is the process of tracing or checking whether a program has (bugs).


 While debugging refers to process of correcting identified program errors.
Types of bugs
 They are two types of bugs that may be encountered when testing a program.
 These are:
i. Syntax errors:
o These are errors that emanate from improper use of language rules e,g
 grammatical mistakes ,
 punctuation
 improper naming of variables and
 misspelling of identifiers and reserved words.
o Syntax errors are detectable and must be corrected before the program runs.

ii. Logical errors:


o They are not detectable by the complier or halts during execution.

Tracing program Errors


 Tracing program errors requires careful step-by-step trace of inputs, processing and output statements.
 The test and debug strategy chosen must be good in order to thoroughly test an algorithm or program before coding.
 Hand tracing or dry run using trace tables is the first step that allows exhaustive testing of an algorithm or program on paper.
 The following is a three-step process of testing an algorithm or program for errors:

1. Dry-run (Desk check)


 Dry-running involves using a trace table to check whether an algorithm or program has errors before writing it in the program
editor.
 A good practice in using a trace table is to go through an algorithm line by line exactly as a computer would.
 This helps the programmer identify syntax and logic errors.

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


3. Test data:
 After the program compiles successfully, the programmer carries out trial runs using test data to check for logic and run-time
errors.
 This is by entering valid and invalid data to test whether the program produces desired output.

Program review and maintenance


 Review and maintenance refers to continuous update and fixing of program errors after installation.
 Fixing and updating the program can be continued until it reaches a point where the program has to be replaced.
 At this point, maintenance stops and the program development life cycle start all over again.

Characteristics of a good program


 Before concluding, this section, we briefly highlight important characteristics of a good computer program:

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.

Programming in Visual Basic

 In programming, BASIC is an acronym for Beginner´s All-purpose Symbolic Instruction Code.


 The foundation of most BASIC versions is the original BASI language developed at Dartmouth College by John G. Kemeny and
Thomas E. Kurtz in 1996.
 The philosophy behind introduction of BASIC programming was to help non-mathematicians learn programming with ease.
 To date, BASIC remains one of the most popular languages with many dialects such as Microsoft Visual Basic (VB) GW-
BASIC,QuickBASIC,Q-BASIC and Turbo Basic Microsoft software development suite known as Microsoft Visual Studio.
 Apart from VB, other dialects of BASIC include Mono, QB64, BASIC, Gambas and FreeBASIC.
 Commercial BASIC languages include PureBasic, PowerBASIC, RealBasic, and True BASIC.
 In mobile device programming, some versions of BASIC have been developed for creating smart-phones and tablets
applications.
 Examples include smart BASIC, Basic!, BASIC-II for iOS devices; and RFO BASIC and Mintoris Basic for Android .
 In this section, we demonstrate how to program in Microsoft Visual Basic.Net.

Microsoft Visual Basic. Net.


 Microsoft Visual Basic. Net,simply referred to as VB. Net is a GUI-based programming language mainly for developing
applications meant to run on Microsoft Windows platforms.
 The main features of VB.Net are:

FORM 3 COMPUTER STUDIES STUDY NOTES |


13
i. It is an event driven programming language.
 An event is a response generated by the program when the user performs an action e.g. a mouse click.
 The response depends on the code of an event procedure.
 An event procedure is a group of self-contained statements that are executed by a computer when an action is performed.
 For example, a mouse click may cause a menu to be displayed on the screen.

ii. It has a collection of tools that are used by programmers.


 These tools are called controls.
 The controls can be accessed easily by clicking their icons on the toolbar.

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.

Basic syntax of VB. Net program


 VB.Net is an object-oriented programming language.
 Oriented programming, a program consists of various objects that interact with each other by means of message passing.
 Objects of the same type belong to the same class just like human beings belong to class called animals.
 Therefore, a VB. Net program can be defined as a collection of objects that communicate with each by sending messages via
methods

Basic concepts relevant to VB.Net programming

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


Variables
 Each object has its unique set of variables that are used to hold data.
 Data values received by methods are assigned to these variables.

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

 'calculates sum is treated as a comment by the compiler.


Structure of VB Program
 A VB.Net program consists of namespace declaration, a class or module, one or more procedures, variables, executable, statements and
comments.
 The program shown below is used to demonstrate the structure and syntax of a Visual Basic program in Microsoft Visual Basic
2010 Express.

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:

VB.Net Startup Window


 This window lets the programmer create a new project or open an existing Visual Basic application.
 In Visual Basic, an application is referred to as a project because it comprises of several files.
FORM 3 COMPUTER STUDIES STUDY NOTES |
15
 To create a new project i.e. Visual Basic application proceed as follows:

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:

New project dialog


 Note that, two environments components used to develop Visual Basic application are the Windows Forms and Console
Applications.
 Forms Application is GUI-based programs while Console applications are command line-based applications.
ii. Select Windows Forms Application, and at the bottom of the dialog box, type the name of the application. For example, the
name of the application HelloWorldApplication that replaces the default WindowsApplication 1 in the inbox.
iii. Once the name of the project is typed (i.e. HelloWorldApplication), click OK button and the Visual Basic Integrated
Development Environment (IDE) is displayed.
 The term IDE refers to a programming environment that provides programmers with several programming features
such as source code editor, debugger and compiler.

VB Integrated Development Environment


Menu and standard toolbar
 The Visual Basic IDE has a menu bar and standard toolbar at the top.
 The menu and the toolbar are used for creating, editing and manipulating the application objects.
FORM 3 COMPUTER STUDIES STUDY NOTES |
 To perform a task using the standard toolbar, simply point to an icon to display tooltip.

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


17
vi. Label
 Label tool is used to place controls that explain the content of other controls on the form.
 For example, if a text box contains surnames, a label against it indicates that surname should be provided.
 This is one of those tools that are frequently used.

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.

viii. Shape tool


 Although not shown on the illustration above, the shape tool is used to draw circles, ellipse, squares and rectangles within the
form.

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.

Drawing a label, text box and a command button

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.

Object Property Settings


Label1 Name LblHello
Text Greetings

Text1 Name txtHello


Text (blank)

Form1 Name FrmGreetings


Text Hello World

Button1 Name CmdOK


Text OK

vii. Double click the command button.


 A code window is displayed where you type the code to be executed once the user clicks the OK button.
FORM 3 COMPUTER STUDIES STUDY NOTES |
19
 The code starts with a class definition called fromHellow, followed by a statement starting with private sub
cmdOK...Because VB.Net is object-oriented, the IDE starts by creating a class within which are methods declared using a
keyword Sub followed by the name of the method e.g. cmdOK.
 A complete code should be as shown in Fig below

A code window

NB: The only code that you are required to type in between the Private Sub and End Sub is the following:

'This program displays Hell World on a Form


txtHello.Text=”Hello, world!”

Explanation of the program


i. The first line is comment that explains what the program does.
 In Visual Basic, a comment starts with single question mark
ii. The second line is an assignment statement.
 i.e. take whatever is on the right side of the =(assignment operator) and replace what is on the left
 In this case, Hello World replace in the textbox named txHello and Greetings will be displayed replaces the blank as shown
below:

Greetings displayed

Running the program


 To execute the Hello World Application and display the Greetings on the form, follow this procedure:
i. Switch to form display by clicking the Form Design tab on the project explorer pane.
ii. On the toolbar, click the Debugging icon.
 Alternatively, press F5 key on the keyboard.
 Hello World Application is executed with Hello World displayed inside the text box as shown in figure above:
iii. To stop running the program, click the stop button on the toolbar that looks like a small box.

Saving VB.Net project


 Saving a project in Visual Basic is a bit different from application software because several files are required to be saved.
 e.g. Project and form module files
 To save a project and forms, follow this procedure:
i. Save the Project file,
 e.g. HelloWorldApplication.
 This is a created project folder in which the project files will be stored because VB.Net creates several files that make up
the application.
ii. To save form, click Save Form As on the file menu.
 The Save As dialog box is displayed in which the name of the form is typed. e.g. formhello
 Click the Save button to save the form as a .vb file
FORM 3 COMPUTER STUDIES STUDY NOTES |
Debugging button
Opening existing project
 VB project can be opened when the Visual Basic starts or from the file menu
 To open project during start up use this procedure:
i. On the Project window, click Open project button.
 A list of folders for each project is displayed
ii. Double click the folder that contains the project to be opened.
 Then select the file which contains the project with extension .vbproj, e.g. HelloWorldApplication.vbproj
iii. Alternatively, if Visual Basic is open, close all other projects and then Click Open Project on the File menu.
 Open project dialog box appears from which a project to be opened is selected.

Adding new form


 Visual Basic project may require the use of more than one form.
 To add form to a project, use this procedure
i. On the Project menu, click the Add Windows Form.
 A dialog box is displayed.
ii. In the dialog, click Windows Form icon and then click the Add button to insert the new form in design view and save it with
preferred file name.
iii. Save the new form with the preferred file name and vb extension.
iv. To make the new form executed after running the program, Click Project Properties on the Project menu.
v. Set the new form as the Startup form and close the properties window.

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.

Rules to follow when declaring variables


i. The variable name must not have more than 255 characters.
ii. The variable name must start with a letter.
iii. The variable may be declared using mixed, lower or upper case because VB is not case sensitive.
iv. A variable name must not be reserved word.
v. A reserved word is a keyword that has special meaning or function in Visual Basic and cannot be used for any other purpose
.e.g. Case, Else, Dim, etc.
vi. Variable names should not have spaces.
vii. If two or more words are to be used to create a variable, use underscore or combine them with each word starting in upper
case
 In Visual Basic, a variable is declared using the reserved word Dim. Dim is the short form of the word dimension.
 It is used to associate variables with specific data type.
 e.g. to declare a variable that stores radius of a circle the following is used

Dim Radius As Integer


 This statement instructs the compiler to reserve memory location named Radius that stores an integer.
 Variables should be explicitly declared using the following data types:-

Data type Description


Integer A whole number with no fractional part. Integers range from -32768 to 32767.
Long integer Numbers which are integers but have a bigger value and range. They range from – 2,
147, 483, 648 to 2, 147, 483,647.
Single A single precision real constant includes a fractional part. The largest value is 3.4x1032
Double It includes a fractional part but has far much larger magnitude than the single real
number constant. However, it cannot be larger than 1.2x10308
String Characters enclosed in quotation marks.
Boolean Data types that have only two logical states i.e. true or false.

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:

“Holiday season” , “345678” , “computer” , “MW7 200”

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.

Example: Area of a Circle

 Create a program that calculates area of a circle given that PI=22/7.


 To write the program, declares PI as constant of double type and radius to be an input variable of single type.
 The program should display the calculated area in a textbox.

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

Object Property Setting


Label 1 Name 1blRadius
Text Radius
Text1 Name TxtRadius
Text (blank)
Text2 Name TxtArea
Text (blank)
Form1 Name FrmCircleArea
Text Circle Area
Button1 Name CmdCalculate
Text Calculate
4. Double click the button and insert the code below in between the private sub and End notes. Note that the dashes
(....) indicate that there is omitted part of the Private Sub method.

Private sub ….... Handles and calculateArea.click


Dim Radius As integer
Dim Area As Double
Const PI as double = 22/7
radius = Val(txtRadius.text) 'convert radius to a numeric value
Area = PI * Radius * radius
txtCicleArea. Text = Str(Area)
End Sub
FORM 3 COMPUTER STUDIES STUDY NOTES |
23
5. Run the program, enter 7 into radius textbox and run and then click the calculate button.

Calculating Area of Circle


Scope declaration

 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:

i. Global variables or constants


ii. Local variables or constants

 A variable or constant that is declared within a function is said to be local.


 This means that the variable can only be accessed within that function.
 However, a variable or constant that is declared outside the function or module but within the same application is said to
be global.
 Such variables can be accessed by other methods within the project.
 In Visual Basic, variables can also be declared as either private or public.
 For example:
i. Private Dim X As Integer
ii. Public Dim Y As String

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

User-defined data types

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

Declaration using suffixes


 Suffixes are special symbols added at the end of a variable or constant in order to associate it with a particular data type.
 This makes programming easier and faster.
 Table below summarises some common suffixes.
Suffix Data type Long declaration Short declaration
% Integer Dim A As Integer A%
! Single Dim X As String X!
$ String Dim Q As String Q $
& Long integer Dim C As String C&
#S Double Dim P As String P #

FORM 3 COMPUTER STUDIES STUDY NOTES |


VB. Net Operators
 In order to write correct mathematical expressions, there is need to understand some of the operators used in Visual
Basic.
 These include arithmetic, relational and logical operators.

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:

Symbol Name Operation


+ Plus sign Addition
- Minus sign Subtraction
* Asterisk Multiplication
/ Slash Division
^ Caret Raise a number to power of
\ Integer division Integer division
MOD Integer remainder Integer remainder

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

FORM 3 COMPUTER STUDIES STUDY NOTES |


25
Dim Num 1, Num 2, Sum As Integer `declare 3 variables as integer ´
Dim Average As double ` declare average As double due to division
`convert input in textbox numeric values
Num 1=Val(number 1. Text)
Num 2=Val(number 2. Text)
Sum =Num 1+Num 2
Average=Sum /2
`display the sum and average in textboxes
txtSum. text=str(sum)
txtAverage. Text=Str(Average)

4. If the program is run, the form such as shown in Figure below is displayed

Using arithmetic operators


Precedence of Arithmetic operators
 Arithmetic operators in Visual Basic have the order of precedence shown in Table below.
 Notice that the order is almost the same as that of BODMAS in mathematics.

Precedence Symbol Explanation

1. Exponentiation Exponential (power)expressions are performed first

2. Multiplication, Division Carried out from left to right in an expression


3. Integer division Carried from left to right after multiplication and division(*,/)
4. Integer remainder Evaluated after integer division
5. Addition and subtraction Evaluated from left to right

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

FORM 3 COMPUTER STUDIES STUDY NOTES |


 The following are examples of relation expression that return true or false

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.

VB. Net Assignment statements


 An assignment statement is an executable statement that assigns whatever is on the right of the assignment operator to the
variable on the left.
 In Visual Basic, the assignment operator is the equal sign(=).
 A variable can be assigned a value as follows:
Variable=Value or Expression

Examples of assignment statements

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


27
Example: Area of triangle
 Write a programme that prompts the user to enter height and base length of a right angled triangle.
 The programme should then calculate the area then displays results.

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.

Calculating area of a triangle


Library functions

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

FORM 3 COMPUTER STUDIES STUDY NOTES |


Function Function Call Description
Round z=Math. Round() Returns the current date
Exp z=Math. Exp(w) Returns the exponential value of ew
Sqr z=Math. Sqr(w) Returns the square root of w
Log z=Math. Log(w) Returns the natural logarithm of w
Str z=Math. Str(w) Converts value to string e.g. Str(6.80)=”6.80”
Cos z=Math. Cos(w) Returns the cosine of w
Abs z=Math. Abs(w) Returns the absolute value of w e.g. Abs(-8)=8
PI z=Math. PI Returns the constant PI of 22/7=3.142...

Using the format function


 The format library function is used to display data in many different formats. Table below shows how to use Format
function in VB:

Expression Sample formatted output


Print Format(16.778994, “##.##”) 16.78(notice the rounding)
Print Format(Now, “mm-dd-yyyy”) 1-20-2005
Print Format(15678, “##,###.00” 15,678.00
Label 1. Caption =Format$(price, “##,###,##”) 10, 630.75

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

Converting numeric string to value


 If a number is entered in a text box is treated as a string in Visual Basis.
 The best way to convert it from string into numeric value is to use the val function.
 The Val function operates on the string and returns a numerical value.
 For example, if the name property of a text box is set to txtLength, then the input in it can read converted into a numeric
value and assigned to variable x as follows:
x= Val(txtLength. Text)
Converting numeric value to string
 To convert a number to string (text) format, use Str() a particular variable has a numeric value and to display this value in
a text box, there is convert it to a string first.
 Suppose that the name of the textbox is txtArea and the numeric value is x then:

textArea. Text= Str(x) `convert x to string and display it in txtArea.

Example: Quadratic function


 Write a program complete with comments in VB that calculates and prints the root of a quadratic equation using the
formula:
Solution
1. Start Visual Basic and choose 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 toolbox to design the form.
3. Change the name and text properties of controls appropriately using a, b, c, root1 and root2.
4. Double click the OK button and insert the code between the Private Sub and End Sub as shown below:
FORM 3 COMPUTER STUDIES STUDY NOTES |
29
Private Sub cmdOK_Click(......) Handles cmdOK.Click
Dim a, b, c, determ As Interge
Dim root1, root2 As Single
`convert coefficients a,b and c input to numeric values
a= Val(txtCoeffa. Text)
b= Val(txtCoeffb. Text)
c= Val(txtCoeffc.Text)
`first compute the value of the determinant
determ=(b^2)- (4*a*c)
roo1=(-b+Math.Sqrt(determ)) / (2*a) `use Sqrt function
´Assign the roots to the output text boxes after rounding off textRoot1.Text=Math.Round(root1,2) Round function to 2dp
textRoot2. Text =Math.Round(root2, 2)
End Sub

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.

Calculating roots of a quadratic equation

 NB: According to precedence rule, b^2 is evaluated first, followed by 4 a*c.


 The difference in the brackets is finally divided by the product of 2 * a.

Control Structures
 Control structures are constructs that determine the logical flow of execution of program statements.

Types of control structures supported by most programming languages


 Sequence,
 Selection and
 Iteration (looping).

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.

FORM 3 COMPUTER STUDIES STUDY NOTES |


Begin
Statement 1
Statement 2
:
Statement n
End
Sequential program

 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

FORM 3 COMPUTER STUDIES STUDY NOTES |


31
Examples: Examination Remarks
 Using pseudocode, design an algorithm for a prompts a user to enter mean score in Computer Studies exam. If the score
is above 50%, the program should display “Pass”.

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.

Private Sub cmdOK- Click(........) Handles cmdOK.Click


Dim score As Integer
Dim comment As String
convert the score in the textbox to value
score=Val(txtScore. Text)
If score >=50 then
comment=Pass”
´display the remark pass or nothing
txtRemark. Text=comment
End If
End Sub

 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 average > 80 THEN


<Statement if true>
ELSE
<statements if false>
END IF

Example: Decision on division


 Write a program that prompts a user to enter two numbers x and y.
 The program the divides x by y as long as y is not zero.
 To avoid division by zero, if y is 0, the program should display an error message “Sorry: Division by Zero”.

FORM 3 COMPUTER STUDIES STUDY NOTES |


Solution
 The following is a sample VB. Net program code that tests whether y is zero to avoid division by zero runtime error.
Private Sub cmdOK_Click(......) Handles cmdOK. Click
Dim comment As String
Dim Grade As Chair
Grade = txtScore. Text 'assign score in textbox to Grade
Select Case Grade
Case “A”, “a”'takes care of uppercase and lower case
comment = “Excellent” 'assign comment excellent
Case “B”, “b”
comment “Goods” `assign comment Good
Case “C”, “c”
comment = “Fair” ´assign comment Fair
Case “D”, “d”
comment= “Poor” ´assign comment Poor
Case Else
comment= “Invalid grade”
End Select
´display the remark to pass or fail
txtRemark. Text=comment
End Sub
 Once the program is run, the form such as shown in Figure below is displayed

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

Example: Marks and Grades


 A Form 3 class teacher requested programming students to write a program that would be used to assign grades in five subjects.
 Using Visual Basic, write a program that would be used to perform the following tasks
a) Enter the names of each student and marks obtained in 5 subjects namely Mathematics, English, Biology, Chemistry and
Computer Studies.
b) After entering each subject mark, the program should calculate the total and average marks for each student.
c) Depending on the average mark obtained, the program should assign grade as follows:
FORM 3 COMPUTER STUDIES STUDY NOTES |
33
i. Between 80and 100: A
ii. Between 70 and 79: B
iii. Between 60 and 69: C
iv. Below 60: D
d) The program should then display the student‟s name, average mark and grade.
Solution
 The following is a simple VB.Net program that implements nested IF selection to assign grade depending on average score obtained in
five subjects.
 Note that the dashes indicate omitted arguments.

Private Sub cmdOK_Click(.......) Handles cmdOK.Click Grade=”A” „assign the grade to A


Dim maths, eng, bio, chem, comp, total As Integer ElseIfscore>=70 Then
Dim Grade As Char Grade=”B” „assign the grade to B
„convert the inputs in the textboxes to values ElseIfscore>=60 Then
maths=Val(txtMaths.Text) Grade=”C” „assign the grade to C
eng=Val(txtEng.Text) Else
bio=Val(txtBio.Text) Grade=”D” „assign the grade D
chem=Val(txtChem.Text) End If
comp=Val(txtComp.Text) „display total, average and grade
„calculate total and average score txtTotal.Text=Str(total)
total=maths+eng+bio+chem+comp txtAvg.Text=Str(score)
score=total/5 txtGrade.Text=Grade
„assign grade based on average score End Sub
Ifscore>=80 Then

 Once the program is run, the form such as shown in Figure below is displayed.

Nested if selection to assign grade


Example: Employee’s Payslip

 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:

Monthly sales Bonus Rate (%)


Above 500 000 15
Between 250 000 and 500 000 10
Below 250 000 5
Solution
 The following is a sample VB.Net program that implements the program for calculating bonuses.
 Note that unlike the nested IF example for assigning grades, in this solution, the inner IF is embedded within IF and
Else parts of the other IF.

FORM 3 COMPUTER STUDIES STUDY NOTES |


Private Sub cmdCalc_Click(.......)Handles cmdCalc.Click bonus = sales*0.05
Const experience_rate As Double=0.05 goodwill = basicpay*experience_rate
Dim basicpay, gross, goodwill, sales As Double gross = basicpay + bonus + goodwill
Dim experience As Single End If
Dim Employees As Single Else „if experience<10 years process gross pay here
„convert the inputs in the textboxes to values If(sales>500000) Then
Employees = txtName.Text bonus = sales*0.15
basicpay = Val(txtBasic.Text) goodwill = basicpay*experience_rate
experience = Val(txtEperience.Text) gross = basicpay + bonus
sales = Val(txtSales.Text) ElseIf(sales>=250000) Then
„use nested if selection to determine gross pay} bonus = sales*0.1
If experience>10 Then „check if experience is goodwill = basicpay*experience_rate
>10yrs gross = basicpay + bonus
If(sales>500000) Then Else
bonus = sales*0.15 bonus = sales*0.05
goodwill = basicpay*experience_rate goodwill = basicpay*experience_rate
gross = basicpay + bonus + goodwill gross = basicpay + bonus
ElseIf(sales>=250000) Then End If
bonus = sales*0.1 txtTotal.Text = Str(gross)
goodwill = basicpay*experience_rate txtCommission.Text = Str(bonus)
gross = basicpay + bonus + goodwill txtExp.Text = (goodwill)
Else End Sub
 Once the program is run, the form such as in Figure below is displayed.

Nested if selection used to compute bonus


Select .. Case
 Similar to nested Ifs, the select case control is used in case there are several alternatives to choose from.
 Unlike the nested IF, select case uses ordinal values only.
 An ordinal value is one that has predecessor and successor such as integers and alphabetic characters.
 For example, the predecessor of 3 is 2 and successor is 4.
 The general structure of Select Case is:
SELECT CASE ordinal_value
CASE 1
<statements>
CASE 2
<statements>
CASE 3
<statements>
CASE ELSE
<statements>
END SELECT

FORM 3 COMPUTER STUDIES STUDY NOTES |


35
Example: Exam performance
 Using Select Case control, write a program that displays the following remarks depending on examination grade awarded:
A: Comment = „Excellent!‟
B: Comment = „Very Good‟
C: Comment = „Good‟
D: Comment = „Poor‟
Solution
 The following is a sample VB.Net program that implements Select Case to assign remarks depending on grade obtained.

Private Sub cmdOK_Click(.......) Handles cmdOK.Click


Dim comment As String
Dim Grade As Char
Grade = txtScore.Text „assign score in the textbox to Grade
Select Case Grade
Case “A:, “a” „takes care of uppercase and lower case
comment = “Excellent” „assign comment excellent
Case “B”, “b”
comment = “Very Good” assign comment Very Good
Case “C”, “c”
Comment = “Good” „assign comment Good
Case “D”, “d”
Comment = “Poor” assign comment Poor
End Select
„display the remark to pass or fail
txtRemark.Text = comment
End Sub
 Once the program is run, the form as shown below is displayed.

Select Case control structure


Looping
 Many real world programs require a statement or group of statements to be executed several times until a condition
is satisfied.
 This repeated execution of program statement(s) is referred to as looping or iteration.
 In other words, a loop is a control structure that causes program statement or statements to be executed several
times.
 For example, assume that you are writing a program that calculates cumulative sum of five subjects for five students.
 To calculate the total score for each student, the program repeatedly reads each student marks in five subject and
then calculates the total.
 Visual Basic language has five types of looping control structures:
a) Do While....Loop
b) While... Wend
c) Do....Loop While
d) Do Until....Loop
e) For.. Next

Do WHILE....LOOP

FORM 3 COMPUTER STUDIES STUDY NOTES |


 The Do While loop is used if a condition has to be met before the statements within the loop are executed.
 This type of loop uses a pre-test condition to determine if statements are to be executed zero or more time.
 For example, in banking, to repeatedly withdraw money on automated teller machine (ATM) a customer must have
sufficient balance in his/her account.
 This transaction can be represented as follows:
Do WHILE balance > 0
Withdraw cash
Update balance
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.

Example: Cumulative sum average


 Write a Visual Basic program that displays total count of the ten numbers (0,2, ...9), their sum and average using
the Do While... Loop.

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

FORM 3 COMPUTER STUDIES STUDY NOTES |


37
While...Wend Loop
 A While...Wend statement is similar to the Do While...Loop statement.
 As with the While loop, this loop continues executing statements within the construct as long as the condition is
true. The general format of While...Wend loop is:

While < condition>


Statements
Wend

 In the previous problem of calculating the sum and average of 10 number, we can replace Do While...Loop with
While.. Wend as follows:

While number <10


sum = sum + number
number = number + 1
Wend

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:

Dim number As Long


number=0
Do Until number >10
number= number + 1
Loop

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... Loop While


 Unlike the While loop, Do..Until loop executes the statements within the loop at least once.
 This is because this type of loop uses a post-test condition at the end of the loop block.
 For example, an ATM cash withdrawal, if Do.. Loop Until is used and the customer balance was zero, the machine
dispenses the cash because the balance is tested after the transaction has been executed as shown below.

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>

FORM 3 COMPUTER STUDIES STUDY NOTES |


Example: Sum and Average

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

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 ´assign initial value of sum is 0
Do ´the loop starts her
sum = sum + number
number = number + 1
txtCount. Text = Str(number)
Loop While number < 10 ´truth condition tested here
Average = sum/number
´display count, sum and average
txtSum. Text = Str(sum)
txtAverage. Text = Str(Average)
End Sub

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:

For count = 0 To 9 STEP 2


<statements>
Next index
 Generally, the For..Next loop that executes the statements within the loop ten times functions as follows:
1. A variable e.g. count is first initialised to the lower limit, e.g. Index is assigned to Ø.
2. The lower limit is then tested against the upper limit e.g. 9.
3. If the lower limit is less than or equal to the upper limit, the program executes
4. The statements inside the body of loop.
5. If the lower limit is less than the upper limit, the count variable is
6. Incremented by 1 and assigned to count, ie. Count = count + 1.
7. If the lower limit is tested against the upper limit and found to be greater, the program exists from the loop.

Worked example: Sum and average


 Using the For.. Next construct, write a program that displays 50 natural numbers on the form i.e (0,2, ...49), their
sum and average.
Solution
 Start Visual Basic and choose New project on the Start Page. Alternatively, add a new form in to an existing project.
 From the toolbox, use Label, Textbox and button tools to design the form.
 Change the name and text properties of the textboxes and command button.
 Double click the count button and insert the code below in the Private Sub section.
Private Sub cmdCount_Click(.....) Handles cmdCount.Click
Dim number As Integer
Dim sum As Integer
Dim Average As Double
sum = 0 'initial value of sum is 0
For x = 0 To 49 ´step is ignored so increments by 1
sum = sum + number
number = number + 1
txtCOUNT. Text = Str(number) ´display count
Next
Average = sum/number
´display count, sum and average
txtSum. Text = Str(Sum)
txtAverage. Text = Str(Average)
8. Once the program is run, the form such as shown in Figure below is displayed.

Fig For... loop

FORM 3 COMPUTER STUDIES STUDY NOTES |

You might also like