Algo Notes S4
Algo Notes S4
Algo Notes S4
TABLE OF CONTENTS
Chapter I. Introduction
I.3 Variables
III.3.1Binary operations
Chapter V. Loops
Chapiter I. Introduction
Algorithm is the sequence of instructions which are involved in solving a given problem
or accomplishment of a given task.
Example:
Var A as Integer
Start
A←5
End
Explanations:
5
I.3 Variables
A variable to be used must first be declared. Declare a variable; means create it by giving
it a name and a data type.
+ Addition
- Subtraction
* Multiplication
/ Division
7
↑ or ̂ Power
!= Not equal to
AND operator
OR operator
To put a value in a variable we use an assignment operator which has the following
symbol: ←
8
A read function is a function which is used for inputs. It helps to receive the value entered
by a user and assign it to a variable.
9
Read( )
Example:
Answer:
Var A as Integer
Start
read(A)
End
Write function is used for Inputs; it displays the content of a variable of displays
messages.
write( )
10
Example:
Answer:
Var B as Integer
Start
B← 5
write(B)
End
11
Transfer A A Out
0 0
1 1
NOT A Out
1 0
0 1
AND A.B A B Out
0 0 0
0 1 0
1 0 0
1 1 1
12
NAND A B Out
0 0 1
0 1 1
1 0 1
1 1 0
OR A B Out
A+B 0 0 0
0 1 1
1 1 1
1 1 1
NOR A B Out
0 0 1
0 1 0
1 0 0
1 1 0
XOR A B Out
0 0 0
0 1 1
1 0 1
1 1 0
XNOR A B Out
0 0 1
0 1 0
1 0 0
1 1 1
13
Different base
Decimal base
B=16 numbers are 0, 1, 2, 3, …,9 , For 10, 11, 12, 13, 14, 15 symbols representing them
are respectively A, B, C, D, E, F
III.3.1Binary operations
0+0=0
0+1=1
14
1+0=1
1 + 1 = 0, retain of 1
1 + 1 + 1 = 1, retain of 1
Examples :
I.4.2 Subtraction
Examples :
I.4.3 Multiplication
0x0=0
0x1=0
1x0=0
15
1 x 1 =1
To convert decimal to binary is very simple, you simply divide the decimal value by 2
and then write down the remainder, repeat this process until you cannot divide by 2
anymore, for example let's take the decimal value 157:
(157)10=(10011101)2
Binary to decimal
Write each value of the binary number times two, from right to left, write the power of
two starting from 0
(10011101)2 =(157)10
To convert an hexadecimal number or octal number into a binary one you take each
number of an hexadecimal number and convert it in a binary and put it on the format of
four bits. For the octal you put it on the format of three bits.
Examples:
Since the hexadecimal number has its equivalent value on 4 bits, we group the binary
number we want to convert in four bits then we search the corresponding number. For the
octal we group three bits.
Examples:
0011 equivalent to 3
17
1101 equivalent to D
1110 equivalent to E
011 equivalent to 3
100 equivalent to 4
101 equivalent to 5
To convert to any base may be done by division or writing in extended notation. Division
is used when converting to a small base. Writing in an extended notation is used when
converting to a greater base.
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.
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.
IV.3.1 If statement
Syntax
If (condition) then
Instructions
End if
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
Go
End if
End
Example 2:
start
Stop
19
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 evaluate to false nothing is done.
Example 3:
Write an algorithm which receives a number and informs the user when it is positive.
Answer:
Var a as integer
Start
Write(“enter a number”)
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
20
If (condition) then
Instructions
Else
Instructions
End if
End
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 the block after else when the condition evaluates to false.
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 false the instruction stop which follows else is executes.
21
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
Write(“enter a number”)
Read(a)
If (a>0) then
else
End if
End
To this question when the condition evaluates true it displays the message the number is
positive when it evaluates to false it displays the message the number is negative.
If statement may be used inside another if statement, in such case we call it a nested if.
Example:
Write an algorithm which receives student note and it displays the grade as follows:
Enswer:
Start
Read(Note)
If (Note>=16) then
Write(“Grade A”)
Else if(Note>=14)then
Write(“Grade B”)
Else if (Note>=12)then
Write(“Grade C”)
Else
Write(“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.
23
Syntax:
Switch(variable)
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
Enswer:
Start
24
Read(Note)
Switch(Note)
Case 1
Case 2
Case 3
Case 4
Default
End switch
End
Chapter V. Loops
What is a loop?
25
Do while loop
The do-While loop execute its statements at least once even if the condition fails for the
first time.
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
26
A=1
Do while A<=10
Write(A)
A=A+1
Loop
End
Syntax:
<Variable>=<start value>
Do
Variable=variable+1
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
27
Write(A)
A=A+1
End
For loop
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:
end for
example:
Write an algorithm which ask a user to enter a number and it displays the 10 next
numbers.
Start
Write(“enter a number”)
Read(I)
I<-I+1
Write(I)
End for
End
Loops in loops refer to what we call nested loops. These are loops that are such that when
one increment by one the other continues inside the first.
Example:
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
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 student 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
We can use one variable called an array to hold all these numbers.
Declaring an array
Syntax
Example:
Variable i is used in a loop to move from indice 0 of the array to indice 19 perfoming
given instructions on the array
Let us declare an array which will hold five numbers and assign to it 5 numbers of our
choice.
Start
30
N(0) <-8
N(1) <- 10
N(2) <- 12
N(3) <- 6
N(4) <- 5
End
Var i as integer
For i=0 to 4 do
Write 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
Write N(i)
31
End for
End
In case we are told that the user will 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
Write N(i)
End for
End
Loop in green color helps to enter data in an array while the array in blue color helps to
display them.
Arrays dimensions
A dimension is a direction in which you can vary the specification of an array's elements.
One-dimensional array
32
Two-dimensional array
Three-dimensional array
Suppose you want to track sales amounts for every day of the present month. You might
declare a one-dimensional array with 31 elements, one for each day of the month, as the
following example shows.
Now suppose you want to track the same information not only for every day of a month
but also for every month of the year. You might declare a two-dimensional array with 12
rows (for the months) and 31 columns (for the days), as the following example shows.
Now suppose you decide to have your array hold information for more than one year. If
you want to track sales amounts for 5 years, you could declare a three-dimensional array
with 5 layers, 12 rows, and 31 columns, as the following example shows.
sorting in algorithm
Selection sort
During each pass, the unsorted element with the smallest (or largest) value is moved to its
proper position in the array.
The number of times the sort passes through the array is one less than the number of
items in the array. In the selection sort, the inner loop finds the next smallest (or largest)
value and the outer loop places that value into its proper location.
Let's look at our same table of elements using a selection sort for descending order.
Remember, a "pass" is defined as one full trip through the array comparing and if
necessary, swapping elements
34
While being an easy sort to program, the selection sort is one of the least
efficient. The algorithm offers no way to end the sort early, even if it begins
with an already sorted list.
Insertion sort
The insertion sort, unlike the other sorts, passes through the array only once. The
insertion sort is commonly compared to organizing a handful of playing cards. You pick
up the random cards one at a time. As you pick up each card, you insert it into its correct
position in your hand of organized cards.
The insertion sort splits an array into two sub-arrays. The first sub-array (such as the
35
cards in your hand) is sorted and increases in size as the sort continues. The second sub-
array (such as the cards to be picked up) is unsorted, contains all the elements to yet be
inserted into the first sub-array, and decreases in size as the sort continues.
Let's look at our same example using the insertion sort for descending order.
The insertion sort maintains the two sub-arrays within the same array. At the beginning
of the sort, the first element in the first sub-array is considered the "sorted array". With
each pass through the loop, the next element in the unsorted second sub-array is placed
into its proper position in the first sorted sub-array.
The insertion sort can be very fast and efficient when used with smaller arrays.
Unfortunately, it loses this efficiency when dealing with large amounts of data.
Buble sort
36
n the bubble sort, as elements are sorted they gradually "bubble" (or rise) to
their proper location in the array, like bubbles rising in a glass of soda. The
bubble sort repeatedly compares adjacent elements of an array. The first and
second elements are compared and swapped if out of order. Then the second
and third elements are compared and swapped if out of order. This sorting
process continues until the last two elements of the array are compared and
swapped if out of order.
When this first pass through the array is complete, the bubble sort returns to
elements one and two and starts the process all over again. So, when does it
stop? The bubble sort knows that it is finished when it examines the entire
array and no "swaps" are needed (thus the list is in proper order). The
bubble sort keeps track of occurring swaps by the use of a flag.
The table below follows an array of numbers before, during, and after a bubble
sort fordescending order. A "pass" is defined as one full trip through the array
comparing and if necessary, swapping, adjacent elements. Several passes have
to be made through the array before it is finally sorted.
The bubble sort is an easy algorithm to program, but it is slower than many
other sorts. With a bubble sort, it is always necessary to make one final "pass"
through the array to check to see that no swaps are made to ensure that the
process is finished. In actuality, the process is finished before this last pass is
made.
37
Quick sort
The shell sort is named after its inventor D. L. Shell. Instead of comparing adjacent
elements, like the bubble sort, the shell sort repeatedly compares elements that are a certain
distance away from each other (d represents this distance). The value of d starts out as half
the input size and is halved after each pass through the array. The elements are compared
and swapped when needed. The equation d= (N + 1) / 2 is used. Notice that only integer
values are used for d since integer division is occurring.
38
Let's look at our same list of values for descending order with the shell sort.
Remember, a "pass" is defined as one full trip through the array comparing and
if necessary, swapping elements.
First Pass: d = (6 + 1) / 2 = 3. Compare 1st and 4th , 2nd and 5th, and 3rd and
6th items since they are 3 positions away from each other))
Second Pass: value for d is halved d = (3 + 1) / 2 = 2. Compare items two
places away such as 1st and 3rd ……
Third Pass: value for d is halved d = (2 + 1) / 2 = 1. Compare items one
place away such as 1st and 2nd …..
Last Pass: sort continues until d = 1 and the pass occurs without any swaps.
}
}
}
return;
}
In order to solve this problem in a proper way, we declare an array without specifying its
size, we fix it later by resizing the array, here we use the instruction redim.
Example: write an algorithm which receive the students notes it calculates their average
and it displays it.
Enswer:
var nb as integer
start
read (nb)
redim Note(nb-1)
…
40
End
At a low level, structured programs are often composed of simple, hierarchical program
flow structures. These are sequence, selection, and repetition:
While making an algorithm a programmer needs not to pay attention on the elements of
the programming language, he has to pay attention to the logic of solution to the problem.
Translating an algorithm in a program using a programming language you need to pay
attention on the elements of that programming language.
#include<stdio.h>
Variable declaration;
Instruction; body
Return 0;
Purpose of flowchart
To write a program starting from a flowchart you need to understand the logic given in
the flowchart and follow the notations of a programming language.
Example:
43
An algorithm is a precise rule (or set of rules) specifying how to solve some problem. An
algorithm lists the steps that must be followed to complete the process. Therefore
various formal methods of describing algorithms have been developed. The simplest of
these is the flowchart.
Exercises:
Question 1 : Write an algorithm which displays your names 60 times using a do…loop
until /5pts
44
Question 2: write an algorithm which receives a number entered by the user and it
display 5 numbers which come after it. For example is the user enter 2 it will display
3,4,5,6,7 /5pts