ALGORITHIM
ALGORITHIM
FUNDAMENTALS
numeration system
All number systems have the same three characteristics: digits, base and
weight
The decimal numeration system uses only ten ciphers (0, 1, 2, 3, 4, 5, 6, 7, 8, and
9) used in "Weighted" positions to represent very large and very small numbers.
Each cipher represents an integer quantity, and each place from right to left in
the notation represents a multiplying constant, or weight, for each integer
quantity.
a) The binary numeration system uses only two ciphers instead of ten as the
decimal numeration system.
Those two ciphers are “0” and “1”. In binary system of numeration, ciphers are
called bit (Binary Digit).
Remark: With n bits we can represent 2n different binary numbers. The higher
H number is given using the following formula. H =2n – 1
The octal number system has a base or radix of eight, meaning that it has eight
possible digits or symbols: 0, 1,2,3,4,5,6,7. How do you count in Octal number
system?
The hexadecimal system uses base 16. Thus, it has 16 possible digit symbols. It
uses the digits
1
How do you count in Hexadecimal number system?
v. Unary encoding
Unary coding, also known as the unary numeral system or thermometer code, is an entropy
encoding that represents a natural number n with a code of length n+1 (or n), usually n ones
followed by a zero (if natural number is understood as non-negative integer) or with n-1 ones
followed by a zero (if natural number is understood as strictly positive integer).
Eg: 5=111110.
Unary coding has several applications in computer science and information theory. For
example, it is used in the design of variable-length codes and Huffman coding
The remainders written in reverse order give the octal equivalent of given
decimal number.
15→F.
The remainders written in reverse order give the hexadecimal equivalent of the
given decimal number.
2
(1 x 8) + (0 x 4) + (1 x 2) + (1 x 1) + (1 x 1/2) + (0 x 1/4) + (1 x 1/8) = 8 + 0 +
2 + 1 + 0.5 + 0 + 0.125 = 11.625
Steps:
For example, binary is the most commonly used non-base 10 system. It is used for coding in
computers. Binary is also known as Base 2. This means it is composed of only 0’s and 1’s.
Addition, subtraction, and multiplication in base 2 are performed similarly to the same way
base 10 does, only smaller, therefore, requires more digits to make up the same number as in
base 10.
In general, the base is defined as the total number of digits that are available in the number
system. This is known as a positional number system. The most commonly used number
system is the decimal system, commonly known as base 10. Its popularity as a system of
counting is most likely due to the fact that we have 10 fingers
The table used to represent the Boolean expression of a logic gate function is
commonly called a Truth Table. A logic gate truth table shows each possible
input combination to the gate or circuit with the resultant output depending
upon the combination of these input(s).
3
For example, consider a single 2-input logic circuit with input variables
labelled as A and B.
There are “four” possible input combinations or 2 2 of “OFF” and “ON” for the
two inputs.
However, when dealing with Boolean expressions and especially logic gate
truth tables, we do not general use “ON” or “OFF” but instead give them bit
values which represent a logic level
“1” or a logic level “0” respectively.
Then the four possible combinations of A and B for a 2-input logic gate is
given as:
For a 2-input AND gate, the output Q is true if BOTH input A “AND” input B
are both true, giving the Boolean Expression of: (Q = A and B).
4
Note that the Boolean Expression for a two input AND gate can be written as:
A.B or just simply AB without the decimal point. 2-input OR (Inclusive OR)
Gate
For a 2-input OR gate, the output Q is true if EITHER input A “OR” input B is
true, giving the Boolean Expression of: (Q = A or B ).
The NAND and the NOR Gates are a combination of the AND and OR Gates
respectively with that of a NOT Gate (inverter). 2-input NAND (Not AND)
Gate
For a 2-input NAND gate, the output Q is true if BOTH input A and input B are
NOT true, giving the Boolean Expression of: (Q = not(A AND B) ).
5
2-input NOR (Not OR) Gate
For a 2-input NOR gate, the output Q is true if BOTH input A and input B are
NOT true, giving the Boolean Expression of: (Q = not (A OR B) ).
As well as the standard logic gates there are also two special types of logic gate
function called an Exclusive OR Gate and an Exclusive-NOR Gate. The
Boolean expression to indicate an
Exclusive-OR or Exclusive-NOR function is to a symbol with a plus sign inside
a circle, ( ).
The switching actions of both of these types of gates can be created using the
above standard logic gates. However, as they are widely used functions they are
now available in standard IC form and have been included here as reference. 2-
input EX-OR (Exclusive OR) Gate
For a 2-input Ex-OR gate, the output Q is true if EITHER input A or if input B
is true, but NOT both giving the Boolean Expression of: (Q = (A and NOT B)
or (NOT A and B)).
6
Summary of 2-input Logic Gates
The following Truth Table compares the logical functions of the 2-input logic
gates above.
The following table gives a list of the common logic functions and their
equivalent Boolean notation.
7
Application of Boolean logic gates
Boolean logic gates are digital devices that are mainly based on the Boolean function. They are used
to carry out logical operations on single or multiple binary inputs and give one binary output. The
most common Boolean operators are AND, OR, and NOT. Each operator has a standard symbol that
can be used when drawing logic gate circuits.
Boolean logic gates have a wide range of applications in digital circuits. They are used in the
architecture of our telephones, laptops, tablets, and memory devices. They are also used in search
engines on the internet. In addition, they are used in the generation of parity generation and checking
units
Data types are used to define the type of data that a variable can hold in a program. They are
used to ensure that the program is free from errors and runs efficiently.
There are two types of data types in JavaScript namely Primitive data types and Non-
primitive data types.
1.Primitive data types: The predefined data types provided by JavaScript language are known
as primitive data types.
Primitive data types are also known as in-built data types.
Eg:
• String: A sequence of characters enclosed in single or double quotes.
• Number: A numeric value, which can be an integer or a floating-point number.
• BigInt: A numeric value with arbitrary precision.
• Boolean: A logical value that can be either true or false.
• Undefined: A variable that has been declared but not assigned a value.
• Null: A variable that has been explicitly assigned the value null.
• Symbol: A unique and immutable primitive value that can be used as the key of an object
property
2.Non-primitive data types: The data types that are derived from primitive data types of the
JavaScript language are known as non-primitive data types. It is also known as derived data
types or reference data types.
Eg: Array, Object etc.
8
1.4 Application of JavaScript operators
JavaScript operators are used to perform specific computations on operands. They are used for
comparing values, performing arithmetic operations, and more. Here is a brief overview of the
different types of JavaScript operators you mentioned:
1. Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
↑or ̂Power
2. Comparison operators (Relational operators)
These operators are used to compare two values and return a Boolean value (true or false). The
most common relational operators are:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
! = Not equal to
3. Logic operators
AND operator (&&)
OR operator (||)
and NOT (!).
4. Assignment operator
To put a value in a variable we use an assignment operator which has the following symbol: ←
These operators are used to assign values to variables. The most common assignment operator
is the equals sign (=)
5. Compound operators:
These operators combine an arithmetic operator with an assignment operator. For example, the
+= operator adds a value to a variable and assigns the result back to the variable.
6. Conditional operators:
These operators are also known as ternary operators because they take three operands. They
are used to assign a value to a variable based on a condition. The most common conditional
operator is the ternary operator (? :)
7. Bitwise operators:
These operators are used to perform bitwise operations on binary numbers. The most common
bitwise operators are AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>)
9
1.5 Algorithm
How to Write an Algorithm?
What is an Algorithm?
1.5.1 Definition
Algorithm is the sequence of instructions which are involved in solving a given
problem or accomplishment of a given task.
It can be translated into a programming language in order to produce the result.
Algorithm is a method of representing the step-by-step logical procedure for solving a
problem.
Algorithms can be represented in two main ways: pseudocode and flowcharts.
Therefore, Algorithm refers to a set of rules/instructions that step-by-step define how a work
is to be executed upon in order to get the expected results.
Algorithm is a well-defined sequential computational technique that accepts a value or a
collection of values as input and produces the output(s) needed to solve a problem.
An algorithm is a step-by-step procedure to solve a problem or perform a task. An algorithm
is independent of the language used. It tells the programmer the logic used to solve the
problem.
1.5.2 There are several reasons why we use algorithms:
• Efficiency: Algorithms can perform tasks quickly and accurately, making them an
essential tool for tasks that require a lot of calculations or data processing.
• Consistency: Algorithms are repeatable and produce consistent results every time
they are executed. This is important when dealing with large amounts of data or complex
processes.
• Scalability: Algorithms can be scaled up to handle large datasets or complex
problems, which makes them useful for applications that require processing large volumes of
data.
• Automation: Algorithms can automate repetitive tasks, reducing the need for human
intervention and freeing up time for other tasks.
Standardization: Algorithms can be standardized and shared among different teams or
organizations, making it easier for people to collaborate and share knowledge.
a. Sorting algorithms: Bubble Sort, insertion sort, and many more. These algorithms
are used to sort the data in a particular format.
b. Searching algorithms: Linear search, binary search, etc. These algorithms are
used in finding a value or record that the user demands.
3. Graph Algorithms: It is used to find solutions to problems like finding the shortest path
between cities, and real-life problems like traveling salesman problems.
4. Recursive Algorithm
This is one of the most interesting Algorithms as it calls itself with a smaller value as inputs
which it gets after solving for the current inputs. In simpler words, It’s an Algorithm that
calls itself repeatedly until the problem is solved.
10
This is another effective way of solving many problems. In Divide and Conquer algorithms,
divide the algorithm into two parts; the first parts divide the problem on hand into smaller
sub problems of the same type. Then, in the second part, these smaller problems are solved
and then added together (combined) to produce the problem’s final solution.
These algorithms work by remembering the results of the past run and using them to find
new results. In other words, a dynamic programming algorithm solves complex problems by
breaking them into multiple simple sub problems and then it solves each of them once and
then stores them for future use.
7. Greedy Algorithm
These algorithms are used for solving optimization problems. In this algorithm, we find a
locally optimum solution (without any regard for any consequence in future) and hope to find
the optimal solution at the global level.
The method does not guarantee that we will be able to find an optimal solution.
This is one of the simplest algorithms in the concept. A brute force algorithm blindly iterates
all possible solutions to search one or more than one solution that may solve a function.
Think of brute force as using all possible combinations of numbers to open a safe.
9. Backtracking Algorithm
a. Finiteness: the algorithm stops after a finite number of instructions are executed.
carried out must be rigorously and unambiguously specified for each case.
c. Input: the algorithm receives input. An algorithm has zero or more inputs, i.e,
d. Output: the algorithm produces output. An algorithm has one or more outputs i.e,
all of the operations to be performed in the algorithm must be sufficiently basic that they can
g. Uniqueness – results of each step are uniquely defined and only depend on the input
11
and the result of the preceding steps.
Advantages of Algorithms
Debug / Error Finding: Every step is independent / in a flow so it will be easy to spot and
fix the error.
Sub-Problems: It is written in a flow so now the programmer can divide the tasks which
makes them easier to code.
Disadvantages of Algorithms
1. Sequence structures
An algorithm can be written in English like sentences or in any standard representation
Sometimes, algorithm written in English like languages are called Pseudo Code.
Example:
Suppose we want to find the average of three numbers, the algorithm
is as follows
Step 1 Read the numbers a, b, c
Step 2 Compute the sum of a, b and c
Step 3 Divide the sum by 3
Step 4 Store the result in variable d
Step 5 Print the value of d
Step 6 End of the program
Example:
Var A as Integer
Start
A=5
12
End
Explanations:
Var A as Integer is the variable declaration line
Start marks the beginning of an algorithm
A=5 the instructions part
End marks the end of an algorithm
1.5.5.1Creating an Algorithm:
Since the algorithm is language-independent, we write the steps to demonstrate the logic
behind the solution to be used for solving a problem. But before writing an algorithm, keep
the following points in mind:
• An algorithm must produce one or more well-defined outputs that are equivalent to
the desired output. After a specific number of steps, algorithms must ground to a halt.
The end
Step 1: Start
Step 2: Get the knowledge of input. Here we need 3 variables; a and b will be the user input
and c will hold the result.
Step 5: Know the problem and find the solution using operators, data structures and logic
We need to multiply a and b variables so we use * operator and assign the result to c.
That is c = a * b
Step 6: Check how to give output, here we need to print the output. So write print c
13
Step 7: End
Step 3: Calculate the sum of all the 3 Subject values and store result in Sum variable (Sum =
S1+S2+S3)
1.5.5.3 Variables
Variable declaration
A variable to be used must first be declared. Declare a variable; means create it by giving it a
IF condition THEN
if body
ENDIF
14
Example: Write an algorithm to find the smallest number between two numbers
Step1: Start
Step 6: End
Step1: Start
Step4: Display C
Step5: Stop
Example 3: Write an algorithm to find the maximum of all the elements present in the array.
Step 2: Declare a variable max with the value of the first element of the array.
Step 4: If max < array element value, change max to new max.
Before an algorithm can be designed, it is important to check that the problem is completely
decomposed. The decomposed problem should consider:
15
the order in which instructions need to be carried out
any decisions that need to be made in the problem
any areas of the problem that are repeated
Only when a problem is properly decomposed and understood can an algorithm design begin.
Programs are developed using programming languages. These languages have specific syntax that
must be used so that the program will run properly.
Pseudocode is not an actual programming language. Instead, it is a simple way of describing a set of
instructions in a manner that resembles a programming language. It has its own syntax, some of which
is very similar to many actual programming languages.
Any algorithms designed using pseudocode will not run unless they are converted into an actual
programming language.
Special Keyword
A read Keyword is a Keyword which is used for inputs. It helps to receive the value entered
by a user and assign it to a variable.
Read
Example:
Answer:
Var A as Integer
Start
Read A
End
16
Print Keyword
Print Keyword is used for Outputs; it displays the content of a variable of displays messages.
Print “ ”
Example:
Answer:
Var B as Integer
Start
B=5
Print B
End
1.5.6.2 Tests
There are situations in which a set of instructions are executed in one situation and entirely
another set of instructions to be executed in a different situation. In this kind of situations, a
decision
control instruction (test) is used. We can define a test as a structure which controls the flow of
instructions of a program during its execution. We can also define it as a structure, which
helps us to evaluate a condition.
1. Structure of a test
The structure of a test is made of two main parts: the part which evaluate a condition, and a
part of one instruction or a block of instructions.
2.1. If statement
Syntax
IF condition THEN
if body
ENDIF
The if statement is used to make a decision. The block of instructions following the if
executes if the decision is true, and the block does not execute otherwise.
Example 1:
start
17
Go
End if
End
Example 2:
start
Stop
End if
End
Each of these statements is conditional. If the condition is true, the instruction following the
condition go in the first example and stop in the second example are executed. In case the
condition
Example 3:
Write an algorithm which receives a number and informs the user when it is positive.
Answer:
Var A as integer
Start
Read A
If A>0 then
End if
End
To this question when the condition evaluates true it displays the instruction: the number is
positive but when it evaluates for false it displays nothing.
Syntax
IF condition THEN
if body
ELSE
18
else body
ENDIF
The if…else statement is used to make a decision and gives the alternative when the condition
evaluates to false. The block of instructions following the if executes if the decision is true,
and
Example 1:
start
Go
else
Stop
End if
End
If the condition is true, the instruction following the condition go is executed, when it
evaluates to
Example 2:
Write an algorithm which receives a number and informs the user whether it is positive or
negative.
Answer:
Var A as integer
Start
Read A
If A>0 then
else
End if
End
19
To this question when the condition evaluates true it displays the message the number is
positive
For eg:
If statement may be used inside another if statement, in such case we call it a nested if.
if body
else if statement
ELSE
else body
ENDIF
For eg:
ELSE
20
ENDIF
END
Example:
Write an algorithm which receives student note and it displays the grade as follows:
Answer:
Start
Read Note
If Note>=16 then
Print “Grade A”
Print “Grade B”
Print “Grade C”
Else
Print “Grade D”
End if
end
A multiple choice using switch helps to solve the problem caused by nested if statement in
case
there are many conditions to be tested. Switch receives a variable then it evaluates it using
several
Case.
Syntax:
Switch(variable)
21
Case 1
Instruction
Case 2
Instruction
….
Case n
Instruction
Default
Instruction
End switch
Example:
Write an algorithm which receives note and displays the student’s grade.
14-16: grade B
12-14: grade C
Answer:
Start
Read(Note)
Switch(Note)
Case 1
Case 2
22
Case 3
Case 4
Default
End switch
End
3.1 Loops
A loop helps to repeat instruction or block of instructions. It assists in the algorithm where
you want to carry out an activity for a certain number of times.
The do-While loop execute its statements at least once even if the condition fails for the first
time. It tests the condition at the end of loop body.
Syntax
Variable=<start value>
Variable=variable+1
Loop
Example:
Write an algorithm which use do while loop and displays numbers from 1 to 10
Answer:
Var A as integer
Start
A=1
Do while A<=10
Write(A)
A=A+1
Loop
End
23
3.1.3. Do… loop Until
Do Until Loop means to do something until the condition becomes TRUE. It is like a logical
function that works based on TRUE or FALSE. This is the opposite of the Do While loop
where
Syntax:
<Variable>=<start value>
Do
Variable=variable+1
Example:
Write an algorithm which use do loop until and displays numbers from 1 to 10
Answer:
Var A as integer
Start
A=1
Do
Print A
A=A+1
End
The for loop is an iterative loop, it specifies some elements about the loop in one single line.
b. End which determine whether its value has reached the number of repetitions desired
The value of the loop counter will be increased each time (iteration), and segment within the
loop
will be executed.
Syntax:
for body
24
ENDFOR
EXAMPLE:
FOR i -> 0 to 20
PRINT i
ENDFOR
example:
Write an algorithm which ask a user to enter a number and it displays the 10 next numbers.
Var I, A as integer
Start
Read I
For A=1 to 10 do
I<-I+1
Print I
End for
End
Loops in loops refer to what we call nested loops. These are loops that are such that when one
Var I, J as Integer
start
For I = 1 To 9 do
For J = 1 To I do
Write(J)
End for
End for
End
WHILE condition
while body
ENDWHILE
25
Example:
i:0
WHILE i <= 2
PRINT i
ENDWHILE
3.4 Handle a table (Array)
An array is a variable with elements of the same data type. To access the array elements, we
use the array index.
For example, if you need to record notes of 20 students in a given course, you will have to
declare 20 variables as follows:
Var N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, N11, N12, N13, N14, N15, N16, N17, N18,
N19, N20 as integer
Writing these variables and assigning values to them is hard.We can use one variable called
an array to hold all these numbers.
Syntax
Example:
Variable i is used in a loop to move from index 0 of the array to index 19 performing given
Let us declare an array which will hold five numbers and assign to it 5 numbers of our choice.
Start
N(0) =8
N(1) = 10
N(2) =12
26
N(3) = 6
N(4) =5
End
Var i as integer
For i=0 to 4 do
Print N(i)
End for
Var i as integer
Start
N(0)=8
N(1) =10
N(2) =12
N(3) =6
N(4) =5
For i=0 to 4 do
Print N(i)
End for
End
In case we are told that the user we enter numbers in array we will use another array for input,
and our algorithm will change as follows:
Var I as integer
Start
For I=0 to 4 do
read N(I)
End for
For I=0 to 4 do
Print N(I)
27
End for
End
3.4.4 Pseudocode
Example of an Algorithm and Pseudocode that add two numbers entered by the User
Algorithm
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
Pseudocode
BEGIN
INPUT s1
INPUT s2 sum=s1+s2
OUTPUT sum
END
Example of an Algorithm and Pseudocode for the greatest number between three
numbers
28
Algorithm
STEP 1: START
STEP 6: STOP
Pseudocode
BEGIN
NUMBER X, Y, Z
INPUT X
INPUT Y
INPUT Z
ELSE
ENDIF
END
Algorithm:
Step1: Start
Else
29
Print Guess not hit
Print hidden
Step 6: Stop
Pseudocode:
BEGIN
READ guess
IF guess=hidden, then
ELSE
PRINT hidden
END IF-ELSE
END
Algorithm:
Step 1: Start
Step 2: Read n
30
Step 10: Stop
Pseudocode:
BEGIN
READ n
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
Algorithm:
Step 1: Start
Step 2: Read n
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
31
Step 7.2: i=i-1 goto step 7
Step 10: If i<n, then goto step 10.1, 10.2 lse goto st 11
Pseudocode:
BEGIN
READ n
READ a[i]
INCREMENT i
END FOR
READ item
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
PRINT a[i]
INCREMENT i
END FOR
END
steps as boxes of various kinds, and their order by connecting these with arrows.
32
A flowchart is the graphical representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program. With
algorithms,
The main purpose of a flowchart is to analyze different processes. Several standard graphics
are applied in a flowchart:
Now that we have the definitions of algorithm and flowchart, how do we use a flowchart to
represent an algorithm?
Algorithms are mainly used for mathematical and computer programs, whilst flowcharts can
be used to describe all sorts of processes: business, educational, personal and of course
algorithms. So flowcharts are often used as a program planning tool to visually organize the
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Flowchart:
33
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)
Algorithm:
Step 3: Print C,
Flowchart:
Example 2: A Flow chart for program that adds two numbers and calculate the average
Flowchart:
Example 3: A Flow chart for program that calculate the largest number between three (3)
numbers
34
Flowchart:
Eg 4: A flowchart for program that display the Multiplication table for a given number N
Task: Q1. Mr. HABUMUGISHA has a work to find all the roots of a quadratic equation
ax2+bx+c=0 1. Draw a flowchart to find all the roots of a quadratic.
Q2. What do you understand by flowchart and list all the standard graphics applied in a
flowchart?
Q3. Write an algorithm to find the average of the marks of 5 subjects inputted from the
keyboard and display the display the following:
If Average<=100 and >=50 the program should display “PASS!!!!!!!!!!!”
If Average<50 the program should display “FAIL!!!!!!!!!!!!!”
Q4. Differentiate algorithm and pseudocode?
END OF LO1
35