2.2.1 Programming Concepts
2.2.1 Programming Concepts
Line: In some languages, such as BASIC or COBOL, a program is divided up into numbered lines.
Each line has a line number & contains one or more statements.
R
Variable: A variable is a quantity named in a program & whose value can change.
Constant: A constant is a value that doesn’t change. In a program it may or may not be given a
KU
name.
Identifier: An identifier is a name invented by the programmer for some data. An identifier can be a
name for a variable, a constant, a file, an array, etc.
Reserved Words: A reserved word is a name that has some special significance to the compiler or
interpreter. The programmer can only use it for its special purpose & can’t use it as an identifier.
A
Expression: An expression is a set of variables, constants & operators (such as +, -, etc) that is to be
evaluated by the computer.
Declaration of a variable serves two purposes: It associates a type and an identifier (or name) with
the variable. The type allows the compiler to interpret statements correctly.
Example: DIM num as integer
Initialization: In computer programming, initialization is the assignment of an initial value for a data
ED
VARIABLES
Syntax: DIM <variable> as <data type>
DIM num, total, avg as Integer
DIM name as String
Dim percentage as Single
CONSTANTS/VALUES
Syntax: <variable> = <constant/value>
Num = 76
Name = “Ahmed Thakur”
Percentage = 89.6
understand and use basic data types: Integer, Real, Char, String and Boolean
Data Types:
There are different data types used in Programming.
R
Data Types Available in [Link]
[Link] provides a wide range of data types. The following table shows all the data types available:
KU
DATA TYPE STORAGE ALLOCATION VALUE RANGE
Depends on implementing
Boolean True or False
platform
A
Char 2 bytes 0 through 65535 (unsigned)
0 through +/-
79,228,162,514,264,337,593,543,950,335
(+/-7.9...E+28) with no decimal point; 0
Decimal 16 bytes through +/-
7.9228162514264337593543950335
with 28 places to the right of the
decimal
ED
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for
negative values
Double 8 bytes 4.94065645841246544E-324 through
HM
1.79769313486231570E+308, for
positive values
-9,223,372,036,854,775,808 through
Long 8 bytes
9,223,372,036,854,775,807(signed)
R
UInteger 4 bytes 0 through 4,294,967,295 (unsigned)
0 through 18,446,744,073,709,551,615
ULong 8 bytes
KU
(unsigned)
A
understand and use the concepts of sequence, selection, repetition, counting and totaling
SEQUENCE
TH
It is a technique of programming that means that instructions/statements must be placed in
appropriate positions in order to execute the correct flow of program.
Sub Main()
Dim num1, num2, tot As Integer
ED
num1 = [Link]()
num2 = [Link]()
tot = num1 + num2
[Link](tot)
HM
[Link]()
End Sub
It is not possible to output the result until all the values are input. Hence the sequence must be
appropriate.
SELECTION
WORD/PHRASE DESCRIPTION
A
Syntax
IF <condition> THEN
<statement if condition is TRUE>
ELSE
R
<statement if condition is FALSE>
ENDIF
KU
Example: Algorithm to check whether the input value is greater than100 and output the message
accordingly.
SET number to 0
INPUT number
IF number > 100 THEN
A
OUTPUT “The entered number is greater than 100”
ELSE
OUTPUT “The entered number is smaller than 100”
ENDIF
END
TH
Visual Basic 2010 (Console Mode) Program:
ED
HM
A
Result of Program:
IF…THEN…ELSEIF…ELSE…ENDIF
This is used to check multiple conditions.
Each ELSEIF works like IF, but must be used within the main structure of IF…ENDIF.
There is no limit of ELSEIFs
If any of the ELSEIF’s condition is met, the rest of the ELSEIFs are not checked.
R
Syntax
IF <condition> THEN
KU
<statement if condition is TRUE>
ELSEIF <condition> THEN
<statement if condition is TRUE>
ELSEIF <condition> THEN
<statement if condition is TRUE>
ELSEIF <condition> THEN
A
<statement if condition is TRUE>
ELSEIF <condition> THEN
<statement if condition is TRUE>
.
.
TH
.
ELSE
<statement if condition is FALSE>
ENDIF
Example: Algorithm to generate a marks sheet and check the grading scheme based on the
following criteria:
ED
D 50 – 59.99
U < 50 (less than 50)
A
R
A 80 – 89.99
B 70 – 79.99
C 60 – 69.99
KU
D 50 – 59.99
U less than 50
A
INPUT eng, comp, isl, math, phy, chem
Tot = eng + comp + isl + math + phy + chem
Per = (Tot/375)* 100
R
KU
A
TH
ED
HM
Result of Program:
A
Syntax
CASE <identifier (variable) OF
<constant>,<constant>,<constant> : <statement>
<constant>,<constant>,<constant> : <statement>
R
<constant>,<constant>,<constant> : <statement>
<constant>,<constant>,<constant> : <statement>
OTHERWISE
KU
<constant> : <statement if identifier/variable is not matched>
ENDCASE
EXAMPLE (NOV 2003 – Q11): The following algorithm inputs air speeds (which must be in multiples of
100) and outputs a suitable message.
A
1. input a speed
2. whole = speed/100
3. case whole of
4. 0,1,2 : result = slow
5. 3, 4, 5, 6 : result = normal
TH
6. 7, 8, 9 : result = high
7. otherwise whole = -1
8. endcase
9. if whole = -1 then
10. output “abnormal reading”
11. else output result, “speed”
ED
(a) Dry run the above algorithm for the following Input data and complete the Output column in
INPUT OUTPUT
(b) State what would happen if line 2 had been missed out of the algorithm.
Variable whole would not be defined,
algorithm would fail/crash, etc.
A
R
KU
A
TH
Result of Program:
ED
HM
A
Example 2: The following example uses a Select Case construction to write a line corresponding to
the value of the variable number.
R
KU
A
TH
Result of Program
ED
REPETITION
WORD/PHRASE DESCRIPTION
FOR….TO….NEXT Loop – (Unconditional) to repeat some task(s) a specific
number of times.
WHILE…DO…ENDWHILE Loop – (Conditional) to repeat some task(s) till a condition
remains TRUE
REPEAT…UNTIL Loop – (Conditional) to repeat some task(s) till a condition
A
remains FALSE
Unconditional Loop: Unconditional loop repeats the tasks unconditionally the specified number of
times.
FOR … TO … NEXT
Syntax
FOR <identifier(variable> = <number> TO <number>
R
<statement>
<statement>
<statement>
KU
NEXT
Example:
Algorithm to output name 10 times. Algorithm to output numbers from 1- 10.
SET a to 0 SET a to 0
FOR a = 1 TO 10 FOR a = 1 TO 10
A
OUTPUT “Ahmed Thakur” OUTPUT a
NEXT NEXT
END END
Program
TH
ED
HM
Result
A
WHILE … DO … ENDWHILE
It is a conditional loop.
Loop continues till the condition remains TRUE.
Condition is check first and the process comes next to it.
Syntax
WHILE <condition> DO
<statement>
<statement>
<statement>
R
<identifier> = <identifier> + <number>
ENDWHILE
KU
Example:
Algorithm to output name 10 times. Algorithm to output numbers from 1- 10.
SET a to 0 SET a to 0
WHILE a < 10 DO WHILE a < 10 DO
a = a + 1 a = a + 1
Output “Ahmed Thakur” OUTPUT a
A
ENDWHILE ENDWHILE
END END
Program
TH
ED
HM
Result
A
Program code that inputs 30 positive numbers and then output the largest number input.
Algorithm (Corrected):
1 Large = 0
2 Counter = 0
R
3 WHILE Counter < 30
4 DO
5 INPUT Num
KU
6 IF Num > Large THEN Large = Num
7 Counter = Counter + 1
8 ENDWHILE
9 PRINT Large
Exercise:
A
June 2015, Paper 22 – Q2
June 2005 – Q13 (b)
November 2002 – Q13
November 2006 – Q9
TH
ED
HM
A
REPEAT… UNTIL
It is a conditional loop.
Loop continues till the condition remains FALSE.
The process comes first, condition is checked next.
Syntax
REPEAT
R
<statement>
<statement>
<statement>
KU
<identifier> = <identifier> + <number>
UNTIL <condition>
Example:
Algorithm to output name 10 times. Algorithm to output numbers from 1- 10.
SET a to 0 SET a to 0
A
REPAT REPAT
a = a + 1 a = a + 1
Output “Ahmed Thakur” Output a
UNTIL a = 10 UNTIL a = 10
END
TH END
Program
ED
HM
Result
A
COUNTING
Counting in 1s is quite simple; use of the statement count = count + 1 will enable counting to
be done (e.g. in controlling a repeat loop). The statement literally means: the (new) count =
the (old) count + 1
It is possible to count in any increments just by altering the numerical value in the statement (e.g.
count = count – 1 counts backwards)
R
Example: Algorithm to count total number of positive and negative entries in 100 inputs.
KU
Algorithm:
SET num, pos, neg to 0
FOR a = 1 TO 100
INPUT num
IF num >= 0 THEN
pos = pos + 1
A
ELSE
neg = neg + 1
ENDIF
NEXT
OUPUT pos, neg
TH
END
pos = pos + 1
Else
neg = neg + 1
End If
HM
Next
[Link](pos & ", " & neg)
[Link]()
TOTALLING
To add up a series numbers the following type of statement should be used:
total = total + number
This literally means (new) total = (old) total + value of number
R
input ten numbers
output the largest number input
output the average value of the input data
KU
Algorithm
10 largest = 0
20 sum = 0, num = 0
30 FOR x = 1 TO 10
40 INPUT num
A
50 IF num > largest THEN largest = num
60 OUTPUT largest
70 sum = sum + num
80 NEXT x
90 average = sum / 10
TH
100 output average
Result/Output
R
KU
A
Example 2: June 2011, Paper 12 – Q10
The following flowchart inputs ten temperatures and outputs the average (mean) temperature and
the number of temperatures which were negative (i.e. < 0).
TH
ED
HM
A
(a) Complete the trace table for this flowchart using the following test data:
5, 11, 16, -4, -10, 8, 10, -3, 17, 10
R
KU
A
TH
Solution:
ED
HM
A
R
KU
A
TH
Result/Output
ED
HM
A
(b) What values are output from the flowchart using the above test data?
Solution: 6, 3
Exercise:
June 2011, Paper 11 – Q5
November 2011, Paper 11 – Q7
R
November 2013, Paper 12 – Q5
June 2015, Paper 21 – Q3
November 2013, Paper 32 – Q1(f)
KU
June 2002 – Q16
November 2004 – Q19
A
some concrete task and is referenced within a larger body of source code. This kind of code item
can also be called a function or a sub-routine. The fundamental role of a procedure is to offer a
single point of reference for some small goal or task that the developer or programmer can trigger
by invoking the procedure itself.
TH
A procedure may also be referred to as a function, subroutine, routine, method or subprogram.
Most programming languages come with a prewritten set of functions that are kept in a library.
ED
The purpose of a function is to take in a number of values or arguments, do some calculations with
those arguments and then return a single result.
perform a specific task, packaged as a unit. This unit can then be used in programs wherever that
particular task should be performed. Subprograms may be defined within programs, or separately
in libraries that can be used by multiple programs. In different programming languages, a subroutine
may be called a procedure, a function, a routine, a method, or a subprogram.
R
Chr, ChrW Returns the character associated with the specified character code.
Returns a zero-based array containing a subset of a String array based on
Filter
specified filter criteria.
KU
Returns a string formatted according to instructions contained in a
Format
format String expression.
Returns an expression formatted as a currency value using the currency
FormatCurrency
symbol defined in the system control panel.
FormatDateTime Returns a string expression representing a date/time value.
A
FormatNumber Returns an expression formatted as a number.
Returns an expression formatted as a percentage (that is, multiplied by 100)
FormatPercent
with a trailing % character.
Returns an integer specifying the start position of the first occurrence of one
InStr
string within another.
TH
Returns the position of the first occurrence of one string within another, starting
InStrRev
from the right side of the string.
Returns a string created by joining a number of substrings contained in an
Join
array.
LCase Returns a string or character converted to lowercase.
Returns a string containing a specified number of characters from the left side
Left
of a string.
ED
StrReverse Returns a string in which the character order of a specified string is reversed.
Returns a string containing a copy of a specified string with no leading or
Trim
trailing spaces.
Returns a string or character containing the specified string converted to
UCase
uppercase.
Example
R
This example uses the UCase function to return an uppercase version of a string.
VB
KU
' String to convert.
Dim LowerCase As String = "Hello World 1234"
' Returns "HELLO WORLD 1234".
Dim UpperCase As String = UCase(LowerCase)
A
Example
This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing
spaces from a string variable. It uses the Trimfunction to strip both types of spaces.
VB
' Initializes string.
TH
Dim TestString As String = " <-Trim-> "
Dim TrimString As String
' Returns "<-Trim-> ".
TrimString = LTrim(TestString)
' Returns " <-Trim->".
TrimString = RTrim(TestString)
' Returns "<-Trim->".
ED
TrimString = LTrim(RTrim(TestString))
' Using the Trim function alone achieves the same result.
' Returns "<-Trim->".
TrimString = Trim(TestString)
HM
Example
This example uses the Mid function to return a specified number of characters from a string.
VB
' Creates text string.
Dim TestString As String = "Mid Function Demo"
' Returns "Mid".
Dim FirstWord As String = Mid(TestString, 1, 3)
' Returns "Demo".
A
Example
This example uses Len to return the number of characters in a string.
VB
' Initializes variable.
Dim TestString As String = "Hello World"
' Returns 11.
R
Dim TestLen As Integer = Len(TestString)
KU
Example
This example uses the InStr function to return the position of the first occurrence of one string within
another.
VB
' String to search in.
A
Dim SearchString As String = "XXpXXpXXPXXP"
' Search for "P".
Dim SearchChar As String = "P"
' Returns 0.
HM
Example
This example shows various uses of the Format function to format values using both String formats
and user-defined formats. For the date separator (/), time separator (:), and the AM/PM indicators
(t and tt), the actual formatted output displayed by your system depends on the locale settings the
code is using. When times and dates are displayed in the development environment, the short time
format and short date format of the code locale are used.
A
Note: For locales that use a 24-hour clock, the AM/PM indicators (t and tt) display nothing.
VB
Dim TestDateTime As Date = #1/27/2001 [Link] PM#
Dim TestStr As String
' Returns current system time in the system-defined long time
format.
TestStr = Format(Now(), "Long Time")
R
' Returns the value of TestDateTime in user-defined date/time
KU
formats.
' Returns "[Link]".
TestStr = Format(TestDateTime, "h:m:s")
' Returns "[Link] PM".
TestStr = Format(TestDateTime, "hh:mm:ss tt")
' Returns "Saturday, Jan 27 2001".
A
TestStr = Format(TestDateTime, "dddd, MMM d yyyy")
' Returns "[Link]".
TestStr = Format(TestDateTime, "HH:mm:ss")
' Returns "23".
TestStr = Format(23)
TH
' User-defined numeric formats.
' Returns "5,459.40".
TestStr = Format(5459.4, "##,##0.00")
' Returns "334.90".
TestStr = Format(334.9, "###0.00")
' Returns "500.00%".
ED
Link: [Link]
R
15 CULng(expression) Converts the expression to ULng data type.
KU
USER DEFINED FUNCTIONS
Programming extends the limits to create any user-defined function if it is not present in the built-in
library.
A
Example: Program to create function to produce square and cube of an input value.
Module Module1
Sub Main()
Dim num, sqr, cub As Integer
TH
num = [Link]
sqr = square(num)
cub = cube(num)
[Link]("Square : " & sqr)
[Link]("Cube : " & cub)
[Link]()
End Sub
ED
End Module
Result/Output
A
The environment
R
KU
A
TH
Starting New Project (Program)
ED
HM
A
Program Editor
R
KU
A
TH
For writing programs in any programming language we need to understand only four basic
concepts:
1. Using variables (Declaration/Initialization)
2. Input and output structures.
ED
3. Selection
4. Loops
Since Visual Basic 2010 is a high level language, therefore programming in it is as easy as writing
pseudocodes.
HM
Any pseudocode can be simply converted into a Visual Basic Program if we simply replace the
pseudocode words with the VB commands.
PSEUDOCODE COMMAND
SET DIM
INPUT/READ [Link]()
OUTPUT/PRINT [Link]
A
IF-ELSE-ENDIF
FOR-TO-NEXT
WHILE-DO-ENDWHILE WHILE – END WHILE
REPEAT – UNTIL DO – LOOP UNTIL
VARIABLE Declaration
Module Module1
Sub Main()
Dim num As Integer
Dim name As String
Dim email As String
Dim phone As String
R
Dim dateofbirth As Date
Dim percentage As Single
KU
num = 2
name = “Ahmed Thakur”
email = “ahmed_thakur@[Link]”
phone = “0300-8268885”
End Sub
A
End Module
INPUT
Module Module1
Sub Main()
TH
Dim num As Integer
Dim name As String
Dim dateofbirth As Date
Dim percentage As Single
num = [Link]()
name = [Link]()
ED
dateofbirth = [Link]()
percentage = [Link]()
End Sub
HM
End Module
OUTPUT
Module Module1
Sub Main()
Dim num As Integer
Dim name As String
Dim dateofbirth As Date
Dim percentage As Single
A
num = [Link]()
name = [Link]()
dateofbirth = [Link]()
percentage = [Link]()
[Link](num)
[Link](name)
[Link](dateofbirth)
[Link](percentage)
End Sub
End Module
R
Module Module1
Sub Main()
KU
Dim num As Integer
[Link]("Enter a number")
num = [Link]()
A
Else
[Link]("Negative number")
End If
[Link]()
End Sub
TH
End Module
ED
HM
A
R
eng = [Link]()
KU
[Link]("Enter marks of Computer....: ")
comp = [Link]()
A
[Link]("Enter marks of Physics.....: ")
phy = [Link]()
gr = "C"
ElseIf per >= 50 And per < 60 Then
gr = "D"
Else
gr = "U"
End If
[Link]()
End Sub
End Module
Sub Main()
For count = 1 To 10
[Link]("Ahmed Thakur")
Next
R
[Link]()
KU
End Sub
End Module
A
Sub Main()
Dim count As Integer
While count < 10
TH
[Link]("Ahmed Thakur")
count = count + 1
End While
[Link]()
End Sub
ED
End Module
Sub Main()
Dim count As Integer
Do
[Link]("Ahmed Thakur")
count = count + 1
Loop Until count = 10
[Link]()
End Sub
A
End Module