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

Programming Essentials 1

Uploaded by

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

Programming Essentials 1

Uploaded by

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

PROGRAMMING ESSENTIALS

PROGRAMMING ESSENTIALS
A COMPREHENSIVE GUIDE
WELCOME TO THE WORLD OF PROGRAMMING.

Programming questions and suggested answers in console application

 Creating a project in console application. First open your vb application (Microsoft visual
studio)

 Click new project then

 Select console application and give your project a name

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.

Then after naming your project the click ok to create a project.

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

\ Integer division(displays the integer part of


division) e.g. 8\3 = 2

^ Exponent ( to the power of)

Mod Displays the remainder part of the


division(9mod 4= 1)

 We first declare the variables. We have types of data types that we user

Data type Description


Integer Any whole number can be negative or positive

Char (character) A single later e.g. ( A)

decimal The number consist of decimals

String Alphanumeric(text)

Single 4 bit number

Double 8 bit number

Boolean True or false , yes or no

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

Syntax for selection

If <condition> then

Vb statements

Else

End if

NB: It is very important that you memorise this syntax

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.

The syntax is as the following

If < condition> then

Vb statements

Elseif <condition> then

Vb statements

Elseif <condition> then

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

If num1 < num2 And num1 < num3 Then


Console.WriteLine(num1 & " is the
smallest")
ElseIf num2 < num3 And num2 < num1 Then

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 have another way of writing the code in selection construct

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.

The syntax for the select case statement is

Select case <variable>

Case 1 <condition>

Vb statements

Case 2 <condition>

Select case <variable>

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

The for loop

The syntax for the for loop is

For <variable name> = range e.g. (1 to 20)

Vb statements

next

Let’s do our first project in iteration

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

15. Write a program that displays the following output

*
**
***
****
*****
*******
********
*********
***********
************
*************
***************

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

16. Write a program that displays the following output


*#
**##
***###
****####
*****######
******#######

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.

Let’s do our first program using the do…loop

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

The last type of iteration that we have is the repeat…until loop


The syntax of this loop is as follows
Do
Vb statements
Loop until <condition>
19.
Total = 10

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

(b) A code that for the algorithm

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

b) The purpose of the algorithm is to produce the number in reverse

c) Write a code for this scenario

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

Console.WriteLine("Please enter a number")


number = Console.ReadLine

If number < 0 Then


Console.WriteLine("negative")
negative = negative + 1
ElseIf number > 0 Then
Console.WriteLine("positive")
positive = positive + 1
Else
Console.WriteLine("neutral")
End If

Next

Console.WriteLine("negative " & negative & " positive


" & positive)
Console.ReadKey()

End Sub

End Module

30 | P a g e
READ NMBER

FOR COUNT = 1 TO NUMBER

READ MARK

IF MARK > 50 THEN OUTPUT COUNT “FAIL”

ELSE IF MARK > 80 THEN OUTPUT COUNT “MERIT”

ELSE OUTPUT COUNT, “PASS”

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

NUMBER COUNTER MARK OUTPUT

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

1. Write a program in console application that displays the following output

*************
************
***********
**********
*********
********
*******
******
*****
****
***

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

*** rewrite this code to produce the shape upside down

2. Write a program that displays the following output

*
**
***
****
*****
*******
********
*********
***********
************
*************
***************

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

3. Write a program that displays the following output


*#
**##

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

Write a code of a pascal’s triangle using the WHILE LOOP


Imports System.Console
Module Module1

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

QSN: WRITE A CODE THAT PRINT A HALF INVERTED PYRAMID OF ASTERISKS


Imports System.Console
Module Module1
Sub Main()
Write("enter the number of rows: ")
Dim rows As Integer = ReadLine()
'written by Kahari Ronald
Dim i As Integer = rows
While i >= 1

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

QSN: Write a program that displays a full pyramid of asterisks


Imports System.Console
Module Module1

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

QSN: Write a program that displays a full inverted pyramid of asterisks


Imports System.Console

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.

Declare marks: integer

Declare names: string

Declare average: double

SUM=0

FOR i =1 TO 10

PRINT ENTER STUNDENT NAME

Read student name

For marks= 1 to 5

Print enter marks

Read marks

Next marks

Sum +=mark

Average =sum/5

Display average

Next i

Readkey

Stop

NB.Write a code for the narration algorithm above


Imports System.Console
Module Module1

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

WriteLine("average is " & average)


ReadKey()
End Sub

End Module

The employees of a company all have 8-character personnel numbers.


An algorithm will do the following
Enter the number and the test if it contains exactly 8 characters, less than 8 characters or
more than 8 characters.
Display appropriate message for each condition.
(i) Produce a code in form of a pseudo code for the above narration.
(ii) Produce a code for your pseudo code in (i) above.
Algorithm
Start

Input number

If number.length =8 Then

Display correct number

elseIf number.length < 8 Then

Display the length too small

Else

Display the length too big

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

Write a code of a palindrome using a function of a palindrome


Nb a palindrome is a word that reads the same as backwards and forward. E.g
mom,racecar

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

A PALINDROME WRITTEN WITH INBUILT FUNCTION

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

Write a function code of a prime number


Nb a prime number which is exactly divisible by one and itself
Imports System.Console
Module Module1
Function isprime(ByVal n As Integer) As Boolean
If n <= 1 Then
Return False
End If
For i As Integer = 2 To CInt(Math.Sqrt(n))
If n Mod i = 0 Then
Return False
End If
Next
Return True

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

ii) line 30 shows this algorithm because this is where the


function calls itself.
iii) FUNCTION Myfunction(byval x : integer):long
Declare I :integer
Declare product : integer =1
If x>0 then
For I =x to 1 step-1
Product =product*1
Next I
Elseif x=0 then
Product=1

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}

IMPLICIT INITIALIZATION: DIM names(5) as string


ARRAY INDEXING AND ACCESS

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

QUESTION FROM SPECIMEN PAPER 2018


QUESTION (4d)
Imports System.Console
Module Module1

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

Next 'closing the loop


Console.WriteLine(" ") 'to create space in console
Console.WriteLine("index " & " element") 'displayin a message
For index = 0 To 5 'opening a loop and setting to start and stop
values
Console.WriteLine(index & vbTab & names(index)) 'display index and
name with index number

Next 'closing loop


Console.WriteLine(names(5)) 'displying results
Console.ReadKey() 'pausing the program
End Sub

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

Dim names(5) As String


Dim i As Integer
WriteLine("enter names: ")
For i = 0 To 5
Write("name " & (i) & ": ")

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

WHAT IS BUBBLE SORT


A SIMPLE SORTING ALGORITHM THAT WORKS BY REPEATEDLY ITERATING
THROUGH A LIST OF ITEMS AND SWAPPING ADJACENT ITEMS IF THEY ARE IN
WRONG ORDER (MIXED ORDER). i.e 54,21,90,76 etc
e.g 21,54,76,90
HOW DOES IT WORKS
1. START AT THE BEGINNING OF THE LIST
2. COMPARE THE FIRST TWO ITEMS. IF THEY ARE IN THE WRONG ORDER,
SWAP THEM
3. MOVE TO THE NEXT PAIR OF ITEMS AND REPEAT THE COMPARISON AND
SWAP IF NECESSARY .
4. CONTINUE THIS PROCCES UNTIL THE END OF THE LIST IS REACHED.
5. REPEAT THE ENTIRE PROCCES UNTIL NO MORE SWAPS ARE NEEDED
INDICATING THE LIST IS SORTED.

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

ANOTHER VERSION OF BUBBLE SORT CODE


Imports System.Console
Module Module1

Sub Main()
WriteLine("how many values do you want to enter: ")
Dim values As Integer = ReadLine()

Dim passes As Integer = 0


Dim temp, j As Integer
Dim data(values - 1) As Integer
For j = 0 To values - 1
Write("input value{0} : ", j + 1)
data(j) = ReadLine()
Next
Dim n As Integer = data.Length
For passes = 0 To n - 1
WriteLine(" pass {0} ", passes + 1)
For j = 0 To n - 2
If data(j) > data(j + 1) Then
temp = data(j)
data(j) = data(j + 1)
data(j + 1) = temp
End If
Next
WriteLine(" ARRAY : " & String.Join(", ", data))

Next
WriteLine("sorted array : " & String.Join(", ", data))
ReadKey()
End Sub

65 | P a g e
End Module

THE OUTPUT SAMPLE

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

Sub Quicksort(ByVal arr() As Integer, ByVal left As Integer, ByVal right


As Integer)
Dim i As Integer
Dim j As Integer
Dim pivot As Integer
Dim temp As Integer
If left < right Then
pivot = arr(left)
i = left
j = right
While i <= j
While arr(i) < pivot And i < right
i = i + 1
End While
While arr(j) > pivot And j > left
j = j - 1
End While

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.

HOW LINEAR SEARCH WORKS


In a linear search, the algorithm starts at the beginning of the collection and
checks each element one by one.
If the current element matches the target value, the search is successful and
the algorithm returns the index of that element.
If the end of the collection is reached and the target value is not found, the
algorithm indicate the target value is not present.

THE LINEAR SEARCH TECHINIQUE


1) Start from the first element of the collection.
2) Compare the current element with the target value.
3) If they match, return the index of the current element.
4) If there is no match, move to the next element.
5) Repeat step2-4 until the target is found or the end collection is reached.

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.

Linear search standard algorithmm


Start
Set count =0
Found =false
Missing =false
Position =0
Enter search-key
Repeat
If search-key =MyArray(count) Then
Set found =True
Print Position of search-key
Elseif search-key < MyArray(count) Then
Set Missing=True
End if
Increment count by 1
Until found =True or count > (numelement-1 )
Stop

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

The sample of output

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

Definition: Binary search is an efficient algorithm for finding an


item from a sorted list of items. It works by repeatedly dividing in
half the portion of the list that could contain the item, until you've
narrowed the possible locations to just one.

*How Binary Search Works:*

1. Start with a sorted list of items.


2. Find the middle point of the list.
3. Compare the target item to the middle item.
4. If the target item is less than the middle item, repeat the process
with the left half of the list.
5. If the target item is greater than the middle item, repeat the
process with the right half of the list.
6. Repeat steps 2-5 until the target item is found or the list is empty.

Key Characteristics:

- Time Complexity: O(log n), making it much faster than linear


search for large lists.
- Space Complexity: O(1), as it only requires a constant amount of
additional memory.
- Requirements: The list must be sorted.

Example Use Cases:

- Finding a specific book in a library catalog.


- Locating a specific record in a database.
- Searching for a word in a dictionary.

Advantages:

- Fast search times, even for large lists.


- Efficient use of memory.

75 | P a g e
Disadvantages:

- Requires the list to be sorted.


- Not suitable for unsorted or dynamic lists.

Implementation Tips:

- Ensure the list is sorted before performing the binary search.


- Use a recursive or iterative approach, depending on your
programming language.
- Handle edge cases, such as an empty list or a target item not
found.

Function BinarySearch(arr() As Integer, target As Integer) As Integer


Dim low As Integer = 0
Dim high As Integer = arr.Length - 1

While low <= high


Dim mid As Integer = (low + high) / 2
If arr(mid) = target Then
Return mid
ElseIf arr(mid) < target Then
low = mid + 1
Else
high = mid - 1
End If
End While

Return -1 ' Target not found


End Function

76 | P a g e

You might also like