Programming Essentials 1
Programming Essentials 1
PROGRAMMING ESSENTIALS
A COMPREHENSIVE GUIDE
WELCOME TO THE WORLD OF PROGRAMMING.
Creating a project in console application. First open your vb application (Microsoft visual
studio)
1|Page
NB: create a folder called programming on desktop where all your projects will be saved, if you
don’t create a folder your projects might be lost.
This is the general syntax of the code using console application. Your code will be typed in between
sub Main () and End sub.
NB: if you delete any later or bracket to this syntax your code will generate errors and it will not run.
So keep this syntax in mind you must know it bye head.
This is the first step of the journey of programming. Programming needs someone who is patient
because at the very first step it will be difficult but eventually you will get it at the end.
1. Our first project is to create a console application that displays the text (hello world)
2|Page
Module Module1
Sub Main()
Console.Write("HELLO WORLD")
Console.ReadKey()
End Sub
End Module
2. you are asked to create a project that allows the user to enter a name and a surname and
then displays the name and surname entered by the user
Module Module1
Sub Main()
'declaring variables
Dim name As String
Dim surname As String
'asking the user to enter a name
Console.WriteLine("what is your name")
'accepting the name
name = Console.ReadLine()
'asking the user to enter a surname
Console.WriteLine("what is your surname")
'accepting the surname
surname = Console.ReadLine()
'displaying the name and surname
Console.WriteLine("l am " & name & vbTab & surname)
Console.ReadKey()
End Sub
End Module
3|Page
Performing calculations
Operator Description
- Subtraction
+ Addition
/ Division
* Multiplication
We first declare the variables. We have types of data types that we user
String Alphanumeric(text)
3. Our first project in calculation is to create a program that allows the user to enter 3 numbers
and calculate the following
Addition
Division
4|Page
Subtraction
Multiplication
Mod
Integer division
Exponent (to the power of)
Module Module1
Sub Main()
'declaring variables
Dim num1, num2, a, b, c, d, e, f, g As Double
'inputing figures
Console.WriteLine("Please enter the first
number")
num1 = Console.ReadLine()
Console.WriteLine("Please enter the second
number")
num2 = Console.ReadLine()
'displaying the answers
'adding two numbers
Console.WriteLine("the sum is")
a = (num1 + num2)
Console.WriteLine(a)
'multiplying two numbers
Console.WriteLine("the product is")
b = (num1 * num2)
Console.WriteLine(b)
'dividing two numbers
5|Page
Console.WriteLine("divided by ")
c = (num1 / num2)
Console.WriteLine(c)
'subtracting two numbers
Console.WriteLine("the difference is")
d = (num1 - num2)
Console.WriteLine(d)
'to the power of
Console.WriteLine("to the power of")
e = num1 ^ num2
Console.WriteLine(e)
'integer division
Console.WriteLine("integer division")
f = num1 \ num2
Console.WriteLine(f)
'mod division
Console.WriteLine("mod division ")
g = num1 Mod num2
Console.WriteLine(g)
Console.ReadKey()
End Sub
End Module
4. You are asked to create a console application that can calculates the area and perimeter of a
circle
6|Page
Module Module1
Sub Main()
'diclaring a constant
Const PI As Single = 22 / 7
'declaring a variable
Dim rad, answ As Single
'asking for the radius from the user
Console.WriteLine("PLEASE ENTER THE RADIUS IN
CENTIMETERS")
'accepting the radius
rad = Console.ReadLine()
'performing calculations
answ = (PI * rad ^ 2)
Console.WriteLine("The area is correct to 2
decimal place " & Format(answ, "####.00"))
answ = (2 * PI * rad)
Console.WriteLine("The perimeter is correct
to 2 decimal place " & Format(answ, "####.00"))
Console.ReadKey()
End Sub
End Module
5. You are asked to create a project that can calculates the volume of a swimming pool
7|Page
Module Module1
Sub Main()
'diclaring variables
Dim l, w, h As Single
Dim volume As Single
'inputing lenght, width and height
respectively
Console.WriteLine("please enter length in
metres")
l = Console.ReadLine()
Console.WriteLine("please enter width in
metres")
w = Console.ReadLine()
Console.WriteLine("please enter height in
metres")
h = Console.ReadLine()
'displaying the volume
'perfoming calculation
volume = (l * w * h)
Console.WriteLine("the volume of the water is
" & Format(volume, "####.00 cubic meters"))
volume = Console.ReadLine()
Console.ReadKey()
End Sub
8|Page
6. Design a project that can convert the temperature entered in degrees to Fahrenheit
Given the formula f = (9 * C)/5 + 32
Module Module1
Sub Main()
'diclaring the variables
Dim celcius As Single
Dim f As Double
'accepting the temprature in degrees celcius
Console.WriteLine("Please enter temperature
in degrees celcius")
celcius = Console.ReadLine()
Console.WriteLine("the temperature in
Fahrenheit is")
'performing calculation
f = ((9 / 5 * celcius) + 32)
Console.WriteLine(f)
f = Console.ReadLine()
Console.ReadKey()
End Sub
End Module
9|Page
B. rewrite the code such that it can convert the temperature
entered in Fahrenheit to degrees Celsius given the formula f =
9/5*C + 32
In programming we have types of constructs. The first one we are going to look at is selection
This is where we give a condition and it is then tested. If the condition is true then execution takes
place but if the condition is false the execution won’t take place. We use the following statements
If <condition> then
Vb statements
Else
End if
7. Write a code that allows the user to enter the age and display a message box whether the
person has grown up or not
NB: below 18 years the person is still under age, above 18 the person has grown up
Imports System.Console
10 | P a g e
Module Module1
Sub Main()
Dim age As Integer
WriteLine("PLEASE ENTER YOUR AGE")
age = ReadLine()
If age < 18 Then
WriteLine("YOU ARE STILL YOUNG AND YOU CANNOT DRIVE")
Else
WriteLine("YOU ARE GROWN UP AND YOU CAN DRIVE ")
End If
ReadKey()
End Sub
End Module
We have nested if statements where we have two or more conditions that we want them to be
tested and executed.
Vb statements
Vb statements
Vb statements
Else
Vb statements
End if
8. Write a code that compare two numbers entered by the user whether there are equal
greater or less than
11 | P a g e
Module Module1
Sub Main()
'diclaring variables
Dim num1, num2, num3 As Integer
'accepting the fegures
Console.WriteLine("please enter first
number")
num1 = Console.ReadLine()
Console.WriteLine("please enter the second")
num2 = Console.ReadLine()
Console.WriteLine("please enter the third
number")
num3 = Console.ReadLine()
'performing comparisons
'testing the conditions
If num1 > num2 And num1 > num3 Then
Console.WriteLine(num1 & " is the
greatest")
ElseIf num2 > num3 And num2 > num1 Then
Console.WriteLine(num2 & " is the
greatest")
ElseIf num3 > num2 And num3 > num1 Then
Console.WriteLine(num3 & " is the
greatest ")
End If
12 | P a g e
Console.WriteLine(num2 & " is the
smallest")
ElseIf num3 < num2 And num3 < num1 Then
Console.WriteLine(num3 & " is the
smallest ")
Else
Console.WriteLine("they are equal")
End If
Console.ReadKey()
End Sub
End Module
9. Write program that can compare word entered by the user that is it a palindrome or not
then it should display an appropriate message
NB: a palindrome is a word that reads that same backwards and forward e.g. dad
Module Module1
Sub Main()
'declaring variables
Dim name, pname As String
Console.WriteLine("please enter the word")
name = Console.ReadLine()
'now i am declaring a function that reverse
the name entered
pname = StrReverse(name)
If name = pname Then
13 | P a g e
Console.WriteLine("it is a palindrome")
Else
Console.WriteLine("it is not a
palindrome")
End If
Console.ReadKey()
End Sub
End Module
e
10. Write a console application that can calculates the roots of a quadratic equation
Imports System.Math
Module Module1
Sub Main()
'declaring variables
14 | P a g e
Dim a, b, c As Integer
Dim x1, x2 As Single
'prompting the user to enter values
Console.WriteLine("Please enter the value of a")
'accepting the data entered
a = Console.ReadLine()
Console.WriteLine("Please enter the value of b")
b = Console.ReadLine()
Console.WriteLine("Please enter the value of c")
c = Console.ReadLine()
'deciding the type of the roots
If (b ^ 2 - 4 * a * c) > 0 Then
Console.WriteLine("the equation has real roots")
ElseIf (b ^ -4 * a * c) < 0 Then
Console.WriteLine("the equation has complex
roots")
ElseIf (b ^ 2 - 4 * a * c) = 0 Then
Console.WriteLine("the equation has repeated
roots")
End If
'performing calculations
x1 = (-b + Sqrt(b ^ 2 - 4 * a * c)) / (2 * a)
'answer to 2 decimal places
Console.WriteLine("the value of x1 is " & Format(x1,
"####.00"))
x2 = (-b - Sqrt(b ^ 2 - 4 * a * c)) / (2 * a)
Console.WriteLine("the value of x2 is " & Format(x2,
"####.00"))
Console.ReadKey()
End Sub
End module
We use the select case statement. This is used in cases where we have many conditions need to be
tested and the conditions can be grouped.
Case 1 <condition>
Vb statements
Case 2 <condition>
15 | P a g e
Vb statements
Case else
Vb statements
End select
11. Create a console application that allows the user to enter the temperature and displays the
appropriate message using the following
0<= freezing
Temperature >=1 and temperature <= 21 moderate
Temperature >= 22 hot
Module Module1
Sub Main()
' diclaring variables
Dim temp As Single
Console.WriteLine("PLEASE INPUT TEMPERATURE
IN DEGREES CELCIUS ")
'accepting the temperature
temp = Console.ReadLine()
'testing the condition
Select Case temp
Case Is <= 0
MsgBox("FREEZING")
Case 1 To 20
MsgBox("MODERATE")
Case Is >= 21
MsgBox("HOT")
Case Else
MsgBox("INVALID DATA ENTERED PLEASE
RETRY ENTERING CORRECTLY")
16 | P a g e
End Select
Console.ReadKey()
End Sub
End Module
12. Design a project that allows the user to enter month of the year and displays the number of
days in that month
Module Module1
Sub Main()
Dim month As String
'declaring the variable
Console.WriteLine("Enter month of the year")
month = Console.ReadLine()
'select the condition
Select Case month
Case "january"
Console.WriteLine("30 days")
Case "february"
Console.WriteLine("28 days")
Case "march"
Console.WriteLine("31 days")
Case "april"
Console.WriteLine("30 days")
Case "may"
Console.WriteLine("31 days")
Case "june"
Console.WriteLine("30 days")
Case "july"
Console.WriteLine("31 days")
Case "august"
Console.WriteLine("31 days")
Case "september"
Console.WriteLine("30 days")
17 | P a g e
Case "october"
Console.WriteLine("31 days")
Case "november"
Console.WriteLine("30 days")
Case "december"
Console.WriteLine("31 days")
Case Else
Console.WriteLine("invalid input !!!
please retry entering correct details")
End Select
Console.ReadKey()
End Sub
End Module
13. Write a program that allows the user to enter a mark and the display an appropriate
message. Use the following information.
70 to 100 = grade A
60 to 69 = grade B
50 to 59 = grade C
40 to 49 = grade D
30 to 39 = grade E
0 to 29 grade F
Module Module1
Sub Main()
'declaring variables
Dim mark As Integer
'prompting the user to enter the mark
Console.WriteLine("please enter your mark")
'accepting the value
mark = Console.ReadLine
'giving the condition
18 | P a g e
Select Case mark
Case 70 To 100
Console.WriteLine("grade A")
Case 60 To 69
Console.WriteLine("grade B")
Case 50 To 59
Console.WriteLine("grade C")
Case 40 To 49
Console.WriteLine("grade D")
Case 30 To 39
Console.WriteLine("grade E")
Case 0 To 29
Console.WriteLine("grade F")
End Select
Console.ReadLine()
End Sub
We have another type of construct which is iteration. This type of construct is used when we
have a work or a task which we want it to be done for a number of times repeatedly. We have three
types of iteration that we have. The first one is
Vb statements
next
19 | P a g e
14. Write a program in console application that displays the following output
*************
************
***********
**********
*********
********
*******
******
*****
****
***
**
*
Module Module1
Sub Main()
Dim x, y As Integer
For x = 1 To 12
For y = 1 To 12 - x
Console.Write("*")
Next
Console.WriteLine()
Next
Console.ReadKey()
End Sub
End Module
20 | P a g e
*** rewrite this code to produce the shape upside down
*
**
***
****
*****
*******
********
*********
***********
************
*************
***************
Module Module1
Sub Main()
'declaring variables
Dim x, y, z, a As Integer
For x = 1 To 12
For y = 12 To x Step -1
'allowing it to leave gaps
Console.Write(" ")
Next y
For z = 1 To x
'printing the output
21 | P a g e
Console.Write("*")
Next
For a = 2 To x
'printing the output
Console.Write("*")
Next
Console.WriteLine()
Next
Console.ReadKey()
End Sub
End Module
Sub Main()
'declaring variables
Dim x, y, z, a, b, c, d, e As Integer
For x = 1 To 12
For y = 12 To x Step -1
'allowing it to leave gaps
Console.Write(" ")
Next y
For z = 1 To x
'printing the output
22 | P a g e
Console.Write("*")
Next
For a = 2 To x
'printing the output
Console.Write("#")
Next
Console.WriteLine()
Next
Console.ReadKey()
End Sub
17. Write a console program that displays the squares of a number and the number that
has been squared in two columns
Module Module1
Sub Main()
'declaring values
Dim n As Integer
'telling the user about the purpose of the
program
23 | P a g e
Console.WriteLine("number sqr of number")
For n = 1 To 12
'performing calcularions
Console.WriteLine(n & vbTab & n ^ 2)
Next n
Console.ReadKey()
End Sub
End Module
Write a program that allows the user to enter a number and displays the numbers
from 1 to that number and the squares of that number
Module Module1
Sub Main()
'declaring variables
Dim num, num1 As Integer
'telling the user to enter the number
Console.WriteLine("please enter a number")
'acceptint the number
num = Console.ReadLine()
'displaying the output in 2 columns
Console.WriteLine("number " & "squares")
'assigning the range
For num1 = 1 To num
'performing the calculation
24 | P a g e
Console.WriteLine(num1 & vbTab & num1 ^
2)
Next
Console.ReadKey()
End Sub
End Module
Now we have done some problems using the for loop structure. We now want to do some
more problems using another type of iteration which is do…loop, do…while loop.
The syntax for do…loop is as follows
DO
VB STATEMENTS
LOOP UNTIL (CONDITION)
KEYPOINTS
THE LOOP EXECUTES AT LEAST ONCE BEFORE CHECKING THE CONDITION.
THE CONDITION IS EVALUATED AFTER EACH ITERATION.
USE DO UNTIL LOOP WHEN YOU KNOW THE MAXIMUM NUMBER OF ITERATIONS
OR
SYNTAX
Do while <condition>
Vb statements
Loop
This type of loop may never execute given the condition false. It test the condition before
execution. If the condition is true then execution takes place but if the condition is false the
execution won’t takes place.
25 | P a g e
18. You are asked to design a console application that adds the numbers between 1 to
10 respectively
Module Module1
Sub Main()
'initialising
Dim num As Integer = 0
'declaring variable
Dim total As Integer
'desplaying the massege to the user
Console.WriteLine("the sum of all integers
between 1 to 10")
'assigning the condition
Do While num <= 10
'performing the calculation
total = total + num
'incrementing by 1
num = num + 1
Loop
'displayng the total
Console.WriteLine(total)
Console.ReadKey()
End Sub
End Module
26 | P a g e
Repeat
Read k
if k >= 2 then
total = total + k
else
k = k*k
total = total + k
endif
print total
until k = 2
print total
end
K total output
10
3 13 13
5 18 18
1 19 19
2 21 21
21
Module Module1
Sub Main()
Dim total As Integer = 10
Dim k As Integer
Do
Console.WriteLine("enter the value of K")
k = Console.ReadLine
If k >= 2 Then
total = total + k
Else
k = k * k
total = total + k
End If
Console.WriteLine(total)
Loop Until k = 2
Console.WriteLine(total)
Console.ReadKey()
27 | P a g e
End Sub
End Module
20. Produce a trace table of the following algorithm using the number 8271
1 INPUT N
2 LET x = INT(N/10)
PRINT N – 10*X
IF x = 0 THEN STOP
N=x
GOTO 2
Number x N
8271 827 1
82 7
8 2
0 8
number X N
8721 872 1
87 2
8 7
0 8
28 | P a g e
Module Module1
Sub Main()
Dim n, x As Integer
Console.WriteLine("please enter a number")
n = Console.ReadLine()
Console.WriteLine("the number in reverse is")
Do
x = Int(n / 10)
Console.Write(n - 10 * x)
n = x
Loop Until x = 0
Console.ReadKey()
End Sub
End Module
21. The following algorithm inputs 20 numbers and outputs how many numbers were positive
(>0) and how many numbers were negative(<0)
1 negative = 1
2 positive = 1
3 for count = 1 to 20
4 input number
5 if number < 0 then negative = negative + 1
6 if number > 0 then positive = positive + 1
7 count = count + 1
8 print negative, positive
9 next count
*** There are 3 errors in this algorithm identify them and suggest corrections to those error
29 | P a g e
Module Module1
Sub Main()
Dim number, count As Integer
Dim negative As Integer = 0
Dim positive As Integer = 0
For count = 1 To 6
Next
End Sub
End Module
30 | P a g e
READ NMBER
READ MARK
ENDIF
ENDIF
NEXT
END
THE ABOVE ALGORITHM IS DESIGNED TO READ A NUMBER OF EXAMINATION MARKS AND PRINT
OUT THE RESULTS FOR EACH OF ONE
COMPLETE A TABLE LIKE THE ONE BELOW IN ORDER TO DRY RUN THE ALGIRITHM WITH DATA
5,72,84,78,45,62,90
The solution is
Module Module1
Sub Main()
Dim mark, number, count As Integer
Console.WriteLine("Please enter the number")
number = Console.ReadLine
For count = 1 To number
Console.WriteLine("please enter mark")
mark = Console.ReadLine()
If mark < 0 Or mark > 100 Then
Console.WriteLine("error")
ElseIf mark < 50 Then
31 | P a g e
Console.WriteLine("fail")
ElseIf mark > 80 Then
Console.WriteLine("Merit")
Else
Console.WriteLine("pass")
End If
Next
Console.ReadKey()
End Sub
End Module
22. Write a program that allows the user to enter 6 numbers throught the keyboard and
the displays the largest of the numbers entered by the user
32 | P a g e
Module Module1
Sub Main()
Dim num, i As Integer
Dim bignum As Integer = 0
For i = 0 To 5
Console.WriteLine("Enter ur number")
num = Console.ReadLine()
If num > bignum Then
bignum = num
End If
Next
Console.WriteLine(bignum)
Console.ReadKey()
End Sub
End Module
*** modify the code above so that it displays the smallest number
23. Write a program that displays the output from the following algorithm
1 x= 1
2 repeat
3 A = x*x
4 output A, X
5X=x+1
6 until x = 3
7 End
Line X A output
1
3 1
4 1 1 1, 1
5 2 1
6 2 1
3 2 4
4 2 4 2, 4
5 3 4
33 | P a g e
Module Module1
Sub Main()
'declaring variables
Dim X As Integer = 1
Dim A As Integer
Do
A = X * X
'the below line allows it to dsplay the output
Console.WriteLine(X & "," & A)
X = X + 1
Loop Until X = 3
Console.ReadKey()
End Sub
End Module
PATTERNS
*************
************
***********
**********
*********
********
*******
******
*****
****
***
34 | P a g e
**
*
Module Module1
Sub Main()
Dim x, y As Integer
For x = 1 To 12
For y = 1 To 12 - x
Console.Write("*")
Next
Console.WriteLine()
Next
Console.ReadKey()
End Sub
End Module
*
**
***
****
*****
*******
********
*********
***********
************
*************
***************
35 | P a g e
Module Module1
Sub Main()
'declaring variables
Dim x, y, z, a As Integer
For x = 1 To 12
For y = 12 To x Step -1
'allowing it to leave gaps
Console.Write(" ")
Next y
For z = 1 To x
'printing the output
Console.Write("*")
Next
For a = 2 To x
'printing the output
Console.Write("*")
Next
Console.WriteLine()
Next
Console.ReadKey()
End Sub
End Module
36 | P a g e
***###
****####
*****######
******#######
Sub Main()
'declaring variables
Dim x, y, z, a, b, c, d, e As Integer
For x = 1 To 12
For y = 12 To x Step -1
'allowing it to leave gaps
Console.Write(" ")
Next y
For z = 1 To x
'printing the output
Console.Write("*")
Next
For a = 2 To x
'printing the output
Console.Write("#")
Next
Console.WriteLine()
Next
Sub MAIN()
Dim rows As Integer
Write("enter number of rows: ")
rows = ReadLine()
Dim i As Integer = 0
37 | P a g e
Dim j As Integer
Dim num As Integer = 1
While i < rows
j = 0
While j <= i
Write(num.ToString.PadLeft(4))
num = num * (i - j) / (j + 1)
j += 1
End While
WriteLine()
i += 1
num = 1
End While
ReadKey()
End Sub
End Module
THE OUTPUT
38 | P a g e
For j As Integer = 1 To i
Write("*")
Next j
WriteLine("")
i -= 1
End While
ReadKey()
End Sub
End Module
The output
39 | P a g e
Sub Main()
Dim rows As Integer
Dim i As Integer = 1
Dim j As Integer
Write("enter number of rows: ")
rows = ReadLine()
While i <= rows
j = 1
While j <= rows - i
Write(" ")
j += 1
End While
j = 1
While j <= i
Write("* ")
j += 1
End While
WriteLine()
i += 1
End While
Write("press any key to exit")
ReadKey()
End Sub
End Module
THE OUTPUT
40 | P a g e
Module Module1
Sub MAIN()
Dim rows As Integer
Write("enter number of rows: ")
rows = ReadLine()
Dim i As Integer = rows
Dim j As Integer
While i >= 1
j = 1
While j <= rows - i
Write(" ")
j += 1
End While
j = 1
While j <= i
Write("* ")
j += 1
End While
WriteLine()
i -= 1
End While
Write("press any key to exit")
ReadKey()
End Sub
End Module
THE OUTPUT
41 | P a g e
Write a program code that print a half pyramid using DO----LOOP UNTIL
Imports System.Console
Module Module1
Sub Main()
Dim rows As Integer = 1 'declaring a variable named rows and
intializing to 1
Do Until rows = 10 'starting a loop until the value of rows is 10.The
loop will execute 10 times
Dim column As Integer = 1 'declaring a variable named column and
intializing to 1
Do Until column >= rows 'starting the inner loop until the given
condition is met
Write("* ") 'print the asterisks
column += 1 'incrementing column by 1
Loop 'the line repeat nested loop until condition is met
WriteLine() 'prints new line, moving the cursor to next line
rows += 1 'incrementing rows by 1
Loop 'the line repeat outer loop until condition is met
ReadKey() 'the line waits for the user to press any key to exit
program
End Sub
End Module
THE OUTPUT
QSN: Write a program code that print a half inverted pyramid using DO----LOOP UNTIL
Imports System.Console
Module Module1
42 | P a g e
Sub Main()
Dim rows As Integer = 10 'declaring a variable named rows and
intializing to 10
Do Until rows = 0 'starting a loop until the value of rows is 0.The
loop will execute 10 to 0
Dim column As Integer = 1 'declaring a variable named column and
intializing to 1
Do Until column > rows 'starting the inner loop until the given
condition is met
Write("* ") 'print the asterisks
column += 1 'incrementing inner loop, column by 1
Loop 'the line repeat nested loop until condition is met
WriteLine() 'prints new line, moving the cursor to next line
rows -= 1 'decrementing the outer loop, rows by 1
Loop 'the line repeat outer loop until condition is met
ReadKey() 'the line waits for the user to press any key to exit
program
End Sub
End Module
THE OUTPUT
QSN: Write a program code that print a FULL pyramid using DO----LOOP UNTIL
Imports System.Console
43 | P a g e
Module Module1
Sub Main()
Dim rows As Integer = 1 'declaring variable named rows and intializing
to 1
Do Until rows = 7 'loop until condition is met
Dim space As Integer = 7 - rows 'declaring variable named space
and intializing to 7 minus number of current rows
Do Until space = 0 'starts nested loop that will continue until
the value of the space is equal to 0
Write(" ") 'prints space to the console
space -= 1 'decrementing value of space by 1
Loop 'repeats the inner loop until condition is met "until space
is 0
Dim column As Integer = 1 'declaring a variable and intializing to
1
Do Until column > rows 'the nested loop will repeat until the
value of column is greater than the current rows value
Write("* ") 'the loop will print asterisks
column += 1 'incrementing the value of column by 1
Loop 'the line will repeats the inner loop until condition is met
WriteLine() 'the line prints new line,moving the cursor to next
line
rows += 1 'incrementing the value of rows by 1
Loop 'the line will repeat the outer loop until condition is met"i.e
rows is =7
ReadLine() 'this line waits for the user to press enter before closing
console window
End Sub
End Module
THE OUTPUT
44 | P a g e
QSN: Write a program code that print a FULL INVERTED pyramid using DO----LOOP UNTIL
Imports System.Console
Module Module1
Sub Main()
Write("Enter number of rows")
Dim number As Integer = ReadLine()
Dim rows As Integer = number
Do Until rows = 0
Dim space As Integer = number - rows
Do Until space = 0
Write(" ")
space -= 1
Loop
Dim column As Integer = 1
Do Until column > rows
Write("* ")
column += 1
Loop
WriteLine()
rows -= 1
Loop
ReadKey()
End Sub
End Module
THE OUTPUT
45 | P a g e
Write an algorithm in pseudo code to calculate the average of set of 5 marks for 10
students entered through the keyboard.
SUM=0
FOR i =1 TO 10
For marks= 1 to 5
Read marks
Next marks
Sum +=mark
Average =sum/5
Display average
Next i
Readkey
Stop
Sub Main()
Dim marks As Integer
Dim names As String
Dim sum As Integer = 0
Dim average As Double
For i = 1 To 10
` WriteLine("name of student " & i)
names = ReadLine()
For m = 1 To 5
WriteLine("mark ")
marks = ReadLine()
Next
sum += marks
46 | P a g e
average = sum / 5
Next
End Module
Input number
If number.length =8 Then
Else
Endif
stop
THE CODE
Imports System.Console
Module Module1
Sub Main()
WriteLine("Enter employee personnel number")
Dim pnumber As String = ReadLine()
If pnumber.Length = 8 Then WriteLine("correct personnel number")
If pnumber.Length < 8 Then WriteLine("The personnel number is too
short")
47 | P a g e
If pnumber.Length > 8 Then WriteLine("the personnel number is too
long")
ReadKey()
End Sub
End Module
The output
Imports System.Console
Module Module1
Function ispalindrome(ByRef instring As String) As Boolean
48 | P a g e
Dim ispal As Boolean
Dim index As Integer
Dim num As Integer
Dim charA, charB As Char
ispal = True
index = 1
num = Int(Len(instring) / 2)
While index <= num And ispal = True
charA = Mid(instring, index, 1)
charB = Mid(instring, Len(instring) - index + 1, 1)
If UCase(charA) <> UCase(charB) Then
ispal = False
End If
index = index + 1
End While
Return ispal
End Function
Sub Main()
Dim NAME As String
For i = 1 To 3
WriteLine("ENTER NAME")
NAME = ReadLine()
WriteLine(ispalindrome(NAME))
Next
ReadKey()
End Sub
End Module
Module Module1
Sub Main()
49 | P a g e
Dim name, pname As String
For i = 1 To 3
Console.WriteLine("enter name")
name = Console.ReadLine
pname = StrReverse(name)
If pname = name Then
Console.WriteLine("it is a palindrome")
Else
Console.WriteLine("it is not a palindrome")
End If
Next
Console.ReadKey()
End Sub
End Module
End Function
Sub Main()
For i = 1 To 6
Write("enter a number: ")
Dim num As Integer = ReadLine()
If isprime(num) Then
50 | P a g e
WriteLine(num & "is a prime number. ")
Else
WriteLine(num & " is not a prime number.")
End If
Next
ReadKey()
End Sub
End Module
Alternatively
Imports System.Console
Module Module1
Sub Main()
Dim number, j As Integer
For i = 1 To 4
WriteLine(" enter number ")
number = ReadLine()
For j = 2 To number
If number Mod j = 0 Then
Exit For
End If
Next
If (j > (number / j)) Then
WriteLine(" {0} is a prime number ", number)
Else
WriteLine(" {0} is not a prime number", number)
End If
Next i
ReadKey()
End Sub
End Module
51 | P a g e
QUESTION EXTRACTED FROM ZIMSEC 2021 COMPUTER SCIENCE
3(a) i
X MyFunction x MyValue
5 MyFunction(4)*5 120
4 MyFunction(3)*4 24
3 MyFunction(2)*3 6
2 MyFunction(1)*2 2
1 MyFunction(0)*1 1
5*4*3*2*1
=120
52 | P a g e
Endif
Myfunction =product
End function
53 | P a g e
ARRAYS
54 | P a g e
ARRAYS
Importance of arrays : arrays enable efficient storage, retrieval and
manipulation of data, making them essential in various applications, such as:
Data storage and processing
Algorithm implementation
Game development
Scientific simulations
DEFINITION OF ARRAY
AN ARRAY is a static data structure which stores and implements a set of data items
of the same data type using the same identifier name
ANOTHER DEFINITION
AN ARRAY is a consecutive group of memory locations that all have the same name
and same type
NB arrays are declared using the following parameters
a. Array name
b. Array size
c. Dimension
d. Data type
DECLARING AND INTIALIZING ARRAYS
To use an array, you must declare its name, data type and size.
SYTANX: DIM arrayname(size) as datatype
EXAMPLE: DIM names(5) as string
INTIALIZING ARRAYS
EXPLICIT INTIALIZATION: DIM names( ) as string ={Ronald, Prince, Tawas, Mnashe, Mcmaye}
Arrays use zero-based indexing, meaning the first elemet is at index zero
55 | P a g e
ACCESSING ARRAY ELEMENTS
Arrayname(index) retrieves the element at the specified index.
Arrayname(index) =value assigns a value to the element at the specified index.
Whe declaring arrays the following declarations represent the same thing
Dim names(4) as string
Dim names(0 to 4) as string
Dim names(1 to 5) as string
The above scenario of declarations have static bounds ,they are just different in writing
but the same .
Arrays have lower and upper bounds and thes elements lie within those bounds
ARRAY TYPES
A ONE DIMENSIONAL ARRAY
A one dimensional array can be thought as list e.g list of lower six computer science
students.
QUESTION FROM
NOVEMBER 2018
QUESTION (4e)
Imports System.Console
Module Module1
Sub Main()
Dim arr(7) As Integer
WriteLine("Enter values for the array:")
For i = 1 To 7
Write("ELEMENT[{0}]: ", i)
arr(i) = ReadLine()
Next
WriteLine(vbCrLf & "ARRAY VALUES:")
For I = 1 To 7
Write("ELEMENT[{0}]: ", I)
Write(arr(I) & vbTab)
Next
ReadKey()
End Sub
End Module
56 | P a g e
A SAMPLE OF OUTPUT
Sub Main()
Dim names(29) As String
Dim mark(29) As Integer
Dim grade(29) As Char
Dim index As Integer
For index = 0 To 30
WriteLine("Enter your name " & index)
names(index) = ReadLine()
WriteLine("Enter your mark " & index)
mark(index) = ReadLine()
Select Case mark(index)
Case 0 To 39
grade(index) = "F"
Case 40 To 44
grade(index) = "E"
Case 45 To 49
grade(index) = "D"
Case 50 To 59
grade(index) = "C"
Case 60 To 69
grade(index) = "B"
Case 70 To 100
grade(index) = "A"
57 | P a g e
Case Else
grade(index) = "ERROR"
End Select
Next
For index = 0 To 30
WriteLine("NAME : " & names(index) & vbTab & "MARK: " & vbTab &
mark(index) & vbTab & "GRADE: " & grade(index))
WriteLine()
Next
ReadKey()
End Sub
End Module
A sample of output
Question
Module Module1
'done by KAHARI RONALD M C
Sub Main()
Dim index As Integer
58 | P a g e
Dim names(5) As String 'declaring array names with array size 0 to 5
to accommodate 6 elements
For index = 0 To 5 ' index loop to iterate 6 times from 0 to 5
Console.WriteLine("enter name " & vbTab & index) 'display a
message and display the index number
names(index) = Console.ReadLine 'accepting the input from the user
End Module
A SAMPLE OF OUTPUT
QUESTION
Write a program tha reads 6 names into an array. The program must display the names in
the same order that they were entered and then in reverse order.
59 | P a g e
Imports System.Console
Module Module1
Sub Main()
Dim names(5) As String
Dim i As Integer
WriteLine("enter names: ")
For i = 1 To 6
Write("name " & (i) & ": ")
names(i) = ReadLine()
Next
WriteLine("names in original order:")
For i = 0 To 5
WriteLine(names(i))
Next
WriteLine("names in revese")
For i = 5 To 0 Step -1
WriteLine(names(i))
Next
ReadKey()
End Sub
End Module
OUTPUT
Alternatively
60 | P a g e
Array.reverse
Imports System.Console
Module Module1
Sub Main()
names(i) = ReadLine()
Next
WriteLine("names in original order:")
For i = 0 To 5
WriteLine(names(i))
Next
Array.Reverse(names)
WriteLine("names in revese")
For i = 0 To 5
WriteLine(names(i))
Next
ReadKey()
End Sub
End Module
Output sample
61 | P a g e
Imports System.Console
Module Module1
Sub Main()
Dim num As Integer
WriteLine("enter number of values to enter")
num = ReadLine()
Dim values(num - 1) As Integer
For i As Integer = 0 To (num - 1)
WriteLine("enter value " & i + 1)
values(i) = ReadLine()
Next
WriteLine(" ")
WriteLine("the results are as follows ")
For t As Integer = 0 To num - 1
WriteLine("index " & t & ":" & vbTab & values(t))
Next
WriteLine()
WriteLine(" the greatest value is: " & values.Max & vbTab & " It is at
array position " & Array.IndexOf(values, values.Max()))
WriteLine()
WriteLine(" the least value is: " & values.Min & vbTab & " It is at
array position " & Array.IndexOf(values, values.Min()))
ReadKey()
End Sub
End Module
62 | P a g e
Output sample
63 | P a g e
KEY POINTS
BUBBLE SORT IS EASY TO IMPLEMENT BUT NOT EFFICIENT FOR LARGE
DATASETS.
IT HAS A WORST-CASE AND AVERAGE TIME COMPLEXITY OF O(n^2),
where n is the number of items.
IT IS STABLE SORT , MEANING THE ORDER OF EQUAL ITEMS IS
PRESERVED.
WRITE A BUBBLE SORT CODE
Imports System.Console
Module Module1
Sub Main()
WriteLine("enter numbers seperated by spaces: ")
Dim input As String = ReadLine() 'read user input as string
Dim numbers As String() = input.Split(" ") 'split input string into an
array of strings using spaces as delimiter
Dim data(numbers.Length - 1) As Integer 'declare an array to store and
convert number
For i = 0 To numbers.Length - 1
data(i) = Convert.ToInt32(numbers(i)) 'convert each string array
to integer and store data in array
Next
WriteLine("original array order ")
For Each num In data
Write(num & " ")
Next
WriteLine()
Dim maxindex As Integer = data.Length - 1
Dim temp As Integer
For pass = 0 To maxindex - 1 'loop through passes
WriteLine("pass" & pass + 1 & ":")
For j = 0 To maxindex - pass - 1 'loop through each element
If data(j) > data(j + 1) Then 'check if the current element is
greater than the next one
'swap elements using a temporary variable
temp = data(j) 'store current element
data(j) = data(j + 1) 'swap elements
data(j + 1) = temp 'restore original element
End If
Next
Write("array after pass" & pass + 1 & ": ")
For Each num In data
Write(num & vbTab & "")
Next
WriteLine()
Next
WriteLine("sorted array order ")
For Each num In data
Write(num & " ")
Next
ReadKey()
End Sub
End Module
64 | P a g e
OUTPUT SAMPLE
Sub Main()
WriteLine("how many values do you want to enter: ")
Dim values As Integer = ReadLine()
Next
WriteLine("sorted array : " & String.Join(", ", data))
ReadKey()
End Sub
65 | P a g e
End Module
QUICK SORT
WHAT IS A QUICK SORT?
QUICK SORT IS HIGHLY EFFICIENT SORTING ALGORITHM THAT EMPLOYS THE
DEVIDE AND CONQUER STRATEGY
A FAST AND EFFICIENT SORTING ALGORITHM THAT USES A DIVIDE AND
CONQUER APPROACH
HOW DOES IT WORKS
1. PIVOT SELECTION: QUICK SORT BEGINS BY SELECTING A “PIVOT”
ELEMENT FROM THE ARRAY. THE CHOICE OF “PIVOT” CAN VARY (e.g.,
FIRST ELEMENT , LAST ELEMENT, RANDOM ELEMENT AND CAN
AFFECT PERFOMANCE.
2. PARTITION THE LIST INTO SUBLIST:
66 | P a g e
THIS PARTITIONING PROCESS ENSURES THAT THE PIVOT IS IN ITS
FINAL SORTED POSITION.
ELEMENTS LESS THAN PIVOT AND
ELEMENT GREATER THAN PIVOT.
3. RECURSIVELY APPLY THE SAME PROCESS TO THE SUNLISTS.
4. COMBINE THE RESULTS TO PRODUCE THE SORTED LIST.
KEY POINTS.
1. QUICK SORT HAS AN AVERAGE TIME COMPLEXITY OF O(n Log n),
MAKING IT SUITABLE FOR LARGE DATASETS.
2. IT HAS A WORST –CASE TIME COMPLEXITY OF O(N^2), BUT THIS
CAN BE MITIGATED BY CHOOSING A GOOD PIVOT.
3. IT IS A COMPARISON-BASED SORT AND NOT A STABLE SORT
A QUICK SORT CODE
THE CODE SHOWING PASSES
Imports System.Console
Module Module1
If i <= j Then
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
i = i + 1
j = j - 1
End If
End While
WriteLine("pass" & left & "-" & right & ":")
For Each num As Integer In arr
Write(num & vbTab)
Next
67 | P a g e
WriteLine()
If left < j Then
Quicksort(arr, left, j)
End If
If i < right Then
Quicksort(arr, i, right)
End If
End If
End Sub
Sub main()
Dim arr(8) As Integer
For i = 0 To 8
WriteLine("enter numbers to be stored " & i)
arr(i) = ReadLine()
Next
Quicksort(arr, 0, UBound(arr))
WriteLine(String.Join(",", arr))
ReadKey()
End Sub
End Module
A SAMPLE OF OUTPUT
68 | P a g e
SEARCHING ALGORITHMS
LINEAR SEARCH: is a straight forward algorithm used to find a specific element
within a collection, such as an array or a list. This method involves examining
each element in the collection sequentially until the desired elements is found
or the entire collection has been searched.
Time complexity
The time complexity of linear search is O(n), where n is the number of
elements in the collection.
This means that in the worst-case scenario , the algorithm may need to check
every element in the collection.
This characteristic makes linear search less efficient for large data sets
compared to more advanced searching algorithms, such as binary search,
which operates in O(log n) time but require collection to be sorted.
ADVANTAGES:
69 | P a g e
Simplicity: linear search is easy to understand and implement, making it a
good choice for begginners.
No sorting required: it can be applied to both sorted and unsorted collections,
which is a significant advantage when dealing with unordered data.
DISADVANTAGES:
Inefficiency: As the size of the collection increases,the time taken to search for
an element also increases linearly, making it inefficient for large datasets.
High complexity: The linear search has a high time complexity of O(n) which
can be a drawback in performance-critical applications.
70 | P a g e
Linear search code versions
Imports System.Console
Module Module1
Sub Main()
Dim numelements As Integer
Dim myarray() As String
Dim searchkey As String
Dim count As Integer = 0
Dim found As Boolean = False
Dim missing As Boolean = False
Dim position As Integer = 0
WriteLine("Array size: ")
numelements = ReadLine()
ReDim myarray(numelements - 1)
For i As Integer = 0 To numelements - 1
WriteLine("Enter element " & (i + 1) & ":")
myarray(i) = ReadLine()
Next
WriteLine("Enter search-key")
searchkey = ReadLine()
Do
If searchkey = myarray(count) Then
found = True
position = count
WriteLine("Item has been found")
WriteLine("position of searchkey: " & (position + 1))
ElseIf searchkey <> myarray(count) Then
missing = True
End If
count += 1
Loop Until found Or count > numelements - 1
If Not found Then
WriteLine("searchkey not found")
End If
ReadKey()
End Sub
End Module
71 | P a g e
Issue: code displayed array position as zero indexed (e.g...,1st element found at
position zero).
Fix: added 1 to the found position to display 1-indexed position(e.g..,1 st
element at position 1)
Why: In visual basic, array indices start at 0 by default. By adding 1, we align
the displayed position with human intuition (1st element at position 1,2nd at
position 2, etc.)
Alternative
Imports System.Console
Module Module1
Sub Main()
Dim numelements As Integer
Dim myarray() As Integer
Dim searchkey As Integer
Dim count As Integer = 0
Dim found As Boolean = False
Dim missing As Boolean = False
Dim position As Integer = 0
WriteLine("Array size: ")
numelements = ReadLine()
ReDim myarray(numelements - 1)
For i As Integer = 0 To numelements - 1
WriteLine("Enter element " & (i + 1) & ":")
myarray(i) = ReadLine()
Next
72 | P a g e
WriteLine("Enter search-key")
searchkey = ReadLine()
Do
If searchkey = myarray(count) Then
found = True
position = count
WriteLine("Item has been found")
WriteLine("position of searchkey: " & (position + 1))
ElseIf searchkey <> myarray(count) Then
missing = True
End If
count += 1
Loop Until found Or count > numelements - 1
If Not found Then
WriteLine("searchkey not found")
End If
ReadKey()
End Sub
End Module
73 | P a g e
74 | P a g e
Binary Search
Key Characteristics:
Advantages:
75 | P a g e
Disadvantages:
Implementation Tips:
76 | P a g e