CS102 Computer Programming I: Algorithms

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

CS102

Computer Programming I

Lecture 2: ALGORITHMS

Bicol University College of Science


CSIT Department
1st Semester, 2019-2020
ACTIVITY 1

1) stand up and assign yourself the number 1


2) pair off with someone standing, add your
numbers together, and adopt the sum as your
new number
3)one of the pair should sit down; the other goes
back to step 2
ALGORITHMS AND THEIR
PROPERTIES
DESIGN, CONSTRUCTION AND
SIMULATION
An introduction to algorithms
Algorithms

Algorithms are the heart of computer science

An algorithm is a description of the steps
necessary to solve a problem

Problem = “task to be performed”

An algorithm is a blueprint for a program

A computer program embodies an algorithm
Definition of algorithm
Dictionary definition
 Oxford Dictionary Definition: A set of mathematical instructions that must be

followed in a fixed order, and that, especially if given to a computer, will help to
calculate an answer to a mathematical problem
 Broadly: a step-by-step method for accomplishing a task

Informal description
 An ordered sequence of instructions that is guaranteed to solve a specific

problem

An algorithm is a list that looks like


– STEP 1: Do something
– STEP 2: Do something
– ...
– STEP N: Stop, you are finished
Definition of algorithm
 An algorithm is a well-ordered collection
of unambiguous and effectively
computable operations that when
executed produces a result and halts in a
finite amount of time
Properties of Algorithm
 Algorithms are well-ordered.
 Algorithms have unambiguous operations.
 Algorithms have effectively computable
operations.
 Algorithms produce a result.
 Algorithms halt in a finite amount of time.
 An algorithm applies to a specific problem
or class of problems
Algorithms are well-ordered
 Sequence definition
 sequence in which the steps are to be carried out
should be unambiguously specified
 ought to have a unique initial instruction, and every
instruction must have a unique successor for given
input data.
Algorithms have unambiguous
operations
 Each operation in an algorithm must be sufficiently
clear so that it does not need to be simplified

 It must be written using computer primitives


– Basic operations used for writing algorithms are known as
primitive operations or primitives.
– When an algorithm is written in computer primitives, then
the algorithm is unambiguous and the computer can
execute it.
 every time an algorithm is presented for execution with
the same input data, the same results are obtained.
Algorithms have effectively computable
operations
 Each operation in an algorithm must be doable, that is,
the operation must be something that is possible to do.

 For computers, many mathematical operations such as


division by zero or finding the square root of a negative
number are impossible.
– These operations are not effectively computable so they
cannot be used in writing algorithms
 A computer cannot perform an instruction if it has
insufficient information or if the result of the
execution of the order is inherently undefined.
Algorithms produce a result
 An algorithm ought to produce at least one
output(otherwise, what use is it?)

 Unless an algorithm produces some result, we can


never be certain whether our solution is correct.

 Only algorithms which produce results can be verified


as either right or wrong.
Algorithms halt in a finite amount of
time

 Finiteness

 Algorithms should be composed of a finite number of


operations and they should complete their execution in
a finite amount of time.

 Every algorithm must reach some operation that tells it


to stop.
An algorithm applies to a specific
problem or class of problems
 Scope of definition

 The range of the inputs has to be predefined


– The range determines the generality of the algorithm
Ways to Express Algorithms
 Structured English

 Pseudocode

 Flowchart
– Symbols, pictorial representation
Sample Algorithm - How to change your
motor oil (Plain English)

 First, place the oil pan underneath the oil plug of


your car. Next, unscrew the oil plug and drain the
oil. Now, replace the oil plug. Once the old oil is
drained, remove the oil cap from the engine and
pour in 4 quarts of oil. Finally, replace the oil cap
on the engine.
Sample Algorithm - How to change your
motor oil (Structured English)

1. Place the oil pan underneath the oil plug of your car.
2. Unscrew the oil plug.
3. Drain oil.
4. Replace the oil plug.
5. Remove the oil cap from the engine.
6. Pour in 4 quarts of oil.
7. Replace the oil cap.
Yet Another Algorithm – The
Swap
 Create an algorithm to interchange the
value of the two cells below:

5 4
Cell A Cell B
Yet Another Algorithm – The Swap and
Its Temporary Solution

1. Copy the contents of cell A to temp.


2. Copy the contents of cell B to cell A.
3. Copy the contents of temp to cell B.

5 1 3
4
Cell A Temp Cell B
Algorithms and Humans
Algorithms are not a natural way of stating a
problem’s solution, because we do not normally
state our plan of action.
We tend to execute as we think about the problem.
Hence, there are inherent difficulties when writing
an algorithm.
We normally tailor our plans of action to the
particular problem at hand and not to a general
problem (i.e. a nearsighted approach to problem
solving)
We usually do not write out our plan, because we
are usually unaware of the basic ideas we use to
formulate the plan. We hardly think about it – we
just do it.
Algorithms and Humans

Computer programmers need to adopt a


scientific approach to problem solving, i.e.
writing algorithms that are comprehensive and
precise.
We need to be aware of the assumptions we
make and of the initial conditions.
Be careful not to overlook a step in the
procedure just because it seems obvious.

Remember, machines do not have judgment, intuition or common


sense!
CATEGORIES OF OPERATIONS
USED TO CONSTRUCT
ALGORITHMS

1. Sequential operations
2. Conditional operations
3. Iterative operations
Sequential operations

- A sequential instruction carries out a single well-defined task;


when that task is finished, the algorithm moves on to the
next operation
- Examples:

Add 1 cup of butter to the mixture in the bowl

Subtract the amount of the check from the current account
balance

Set the value of x to 1
Conditional operations

- They ask a question and then select the next


operation to be executed on the basis of the
answer to that question
- Examples:

If the mixture is too dry, then add one-half cup of water to
the bowl

If the amount of the check is less than or equal to the
current account balance, then cash the check; otherwise,
tell the person that the account is overdrawn

If x is not equal to 0, then set y equal to 1/x; otherwise,
print an error message that says we cannot divide by 0
Iterative operations
- They tell us to go back and repeat the execution of
a previous block of instructions
- Examples:

Repeat the previous two operations until the mixture has
thickened

While there are still more checks to be processed, do the
following five steps

Repeat steps 1, 2, and 3 until the value of y is equal to 11
Basic operations/instructions for
computers

A computer can transfer data from one place to another.

A computer can input data from an input device (a keyboard
or a mouse, for example) and output data to an output
device (a screen, for example).

A computer can store data into and retrieve data from its
memory and secondary storage.

A computer can compare two data values for equality or
inequality.

A computer can perform arithmetic operations (addition and
subtraction, for example) very quickly.
How to write Pseudocode

An algorithm can be written in pseudocode using six (6) basic


computer operations:

• A computer can receive information.


Typical pseudocode instructions to receive information are:
Read name
Get name
Read number1, number2

• A computer can output (print) information.


Typical pseudocode instructions are:
Print name
Write "The average is", ave

• A computer can perform arithmetic operation


Typical pseudocode instructions:
Add number to total, or
Total = Total + Number
Ave = sum/total
(Pseudocode...Cont'd)
● A computer can assign a value to a piece of data:
e.g. to assign/give data an initial value:
Initialize total to zero
Set count to 0
To assign a computed value:
Total = Price + Tax

• A computer can compare two (2) pieces of information and select one of
two alternative actions.
Typical pseudocode e.g.
If number < 0 then
add 1 to neg_number
else
add one to positive number
end-if

• A computer can repeat a group of actions.


Typical pseudocode e.g. OR
Repeat until total = 50 while total < = 50 do:
read number read number
write number write number
add 1 to total
end-while
end-repeat
ALGORITHM SIMULATION

SIMULATION

- An imitation of the processes and its results

- A trial run or dry run


Simulation Exercise 01

Simulate the
algorithm on the Algorithm Add
right and determine
the following 1.input (a, b);
 What is the 2.sum = a + b;
display if the input
is
3.display (sum);

9 and 3

-5 and 10

8 and -18
 What is the
algorithm for?
Simulation Exercise 02
• Algorithm Swap 
Describe the
1. input x, y; behaviour of the
algorithm.
2. tmp = x; 
Suggest an
3. x = y; alternative
4. y = tmp; algorithm
5. display (x,y);
Simulation Exercise 03
1. i = 1; 
What does the algorithm
2. j = 1; do?
3. display (“*”); 
What is the screen
4. j = j + 1; output?
5. Is j greater than i? 
What happens if
a. Yes:  line 6 of the algorithm
i. display(‘\n”); is replaced by “Is i
ii. goto 6; equals 4” ?
b. No: goto 3  If line 3 is replaced by
6. Is i equals 6? “display(i);”?
a. Yes: Stop;
b. No:
i. i = i+1;
ii. goto 2;
ACTIVITY 2
Use pseudocode in writing your algorithms. If not enough
information is provided, please make your necessary assumptions
and write it before the algorithm.

1. Design an algorithm that will compute the area of a triangle.


2. Write an algorithm that computes and displays the sum and
product of two integer numbers.
3. Juan has an assignment which asks him to find the area of a
circle with the radius as the only given data. Write an algorithm
that will help Juan solve his assignment.
4. Make an algorithm that will display the largest among the
three numbers.
5. Write an algorithm that determines if the three numbers are
all equal.
End of Lecture 2

You might also like