0% found this document useful (0 votes)
22 views114 pages

COS 102 - Merged

The document discusses algorithms, their role in computer science, and their applications, emphasizing their importance in problem-solving and data processing. It covers various types of algorithms including searching and sorting algorithms, as well as the fundamental concepts of sequence, selection, and repetition in algorithm design. Additionally, it introduces data structures, decision tables, and arrays, highlighting their significance in organizing and managing data efficiently.

Uploaded by

67jhfwmz22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views114 pages

COS 102 - Merged

The document discusses algorithms, their role in computer science, and their applications, emphasizing their importance in problem-solving and data processing. It covers various types of algorithms including searching and sorting algorithms, as well as the fundamental concepts of sequence, selection, and repetition in algorithm design. Additionally, it introduces data structures, decision tables, and arrays, highlighting their significance in organizing and managing data efficiently.

Uploaded by

67jhfwmz22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

ALGORITHMS

NINAN O. D.
• Algorithms are a set of well-defined rules/instructions used to solve a specific
problem.
• Each algorithm is unique in the way it tackles a problem, taking into account
factors like the problem size, resources, and efficiency, among others.

Role of Algorithms in Computer Science


• Algorithms help to reduce the complexity of a problem by breaking it down
into smaller, manageable sub-problems.
• They are essential for data processing and ensuring efficient memory usage.
• They ensue the security and protection of data, especially in areas like
cryptography.
• Algorithms are vital in data search for large databases.
Data structures
• Data structures are a way of organising data in a computer so that it can be
used efficiently.
• An algorithm is a step-by-step procedure designed to perform specific
operations.
• As a pair, data structures and algorithms are a fundamental aspect of
computer science, facilitating efficient problem-solving strategies.
• .Algorithms utilise data structures to solve computational problems,
• Choosing the right data structure can mean the difference between a solution
and an optimal solution.
• A well-chosen data structure can improve an algorithm's efficiency
dramatically.
Searching Algorithms
• searching algorithms are designed to find a particular item in a data
structure.
• Searching algorithms are designed to retrieve information stored within a
data structure, such as an array or a graph.
• The choice of searching algorithm often depends on the structure of your
data and the nature of the query.
• This algorithm returns the position if the element is found; otherwise, it
returns -1 or NULL.
• There are primarily two types of searching algorithms:
- Sequential Search (or Linear Search) and
- Interval Search (or Binary Search).
• Linear Search: A simple approach, this algorithm starts at the beginning of a
list and checks every element until it finds the one it's looking for.
• Binary Search: Only applicable to a sorted list or array, this algorithm divides
the list into two halves and determines if the desired value is in the first half
or second half. It continues halving until it locates the item.
• Binary Search requires the list to be sorted, while Linear Search does not.
• Euclidean Algorithm: Used for finding the greatest common divisor (GCD) of
two numbers.
• Sorting Algorithms
• sorting algorithms arrange elements in a specific order within a data
structure.
• sorting algorithms reorganise data in a particular format, often ordering the
elements in ascending or descending order.
• The most suitable sorting algorithm depends on a mixture of elements, the
structure of the data, and the system's memory.
• A Sorting Algorithm is a method that rearranges elements in a list according
to a certain order such as numerical or lexicographic.
• Sorting algorithms are categorised as either
- comparison-based (such as Bubble Sort, Quick Sort, and Merge Sort) or
- non-comparison based (like Counting Sort or Radix Sort).
• Bubble Sort: Repeatedly steps through the list, compares adjacent elements,
and swaps them if they are in the wrong order.
• Quick Sort: Divides the list based on a pivot element and sorts two
reduced arrays independently.
• Merge Sort: Divides the list into equal halves, sorts them, and then merges
them.
• Counting Sort: Assumes that the input elements are an integer array within a
specific range and counts the occurrence of each number.
• Radix Sort: Performs digit-by-digit sort starting from least significant digit to
most significant digit.
• Hash Sort: uses a Hash function (a search-optimised function) to distribute
elements across an array based on their key values. This method of sorting
allows for quickly locating elements during a search due to the uniform
distribution of data.
Applications of Algorithms
• Digital Maps and Route Planning: e.g. Dijkstra’s algorithm which finds the
shortest path between two points on a graph.
• Search Engines: Search engines like Google use complex algorithms to
deliver the most relevant results for queries.
• PageRank, for example, is an algorithm used by Google Search to rank
websites in its search engine results.
• Online Shopping and Recommendations - recommendation algorithms.
• Medical Imaging: In the healthcare industry, image processing algorithms
help analyse and interpret medical images like X-rays, MRIs, or CT scans.
• cryptography, weather prediction, airline reservations, social networking
etc .
• INTRODUCTION TO PROBLEM SOLVING

• An algorithm is a sequence of simple steps that can be followed to solve a


problem.
• These steps must be organized in a logical, and clear manner.
• Algorithms are designed using three basic methods of control: sequence,
selection, and repetition.
• Sequential control.
• Sequential Control means that the steps of an algorithm are carried out in a
sequential manner where each step is executed exactly once.
• Sequential execution of code statements (one line after another) -- like
following a recipe
• Let’s look at the following problem:
• We need to obtain the temperature expressed in Farenheit degrees and
convert it to degrees Celcius.
• An algorithm to solve this problem would be:
1. Read temperature in Farenheit
2. Apply conversion formula
3. Display result in degrees Celcius
• In this example, the algorithm consists of three steps.
• Also, note that the description of the algorithm is done using pseudocode.
• A pseudocode is a mixture of English (or any other human language), symbols,
and selected features commonly used in programming languages.
• Here is the above algorithm written in pseudocode:

READ degrees_Farenheit
degrees_Celcius = (5/9)*(degrees_Farenheit - 32)
DISPLAY degrees_Celcius

• Another option for describing an algorithm is to use a graphical representation


in addition to, or in place of pseudocode.
• The most common graphical representation of an algorithm is the flowchart.
• Example : Write an algorithm to calculate the area of a rectangle
• Algorithm:
Step 1: Start
Step 2: Input length and breadth
Step 3: area = length * breadth
Step 4: print area
Step 5: stop

Ex. Draw the flowchart for the algorithms.


• Selection control.
• In Selection Control only one of a number of alternative steps is executed. In
data processing, it is often required to select one of the two different
alternatives depending on the prevailing condition.
• To select, a test is made of a condition that can either be true or false.
• If the condition is true, then one path is followed; and if it is false then the
other path is followed.
• The following algorithm and flowchart do illustrate the selection component.
if the condition is true
then follow step A
else follow step B
end if
• Flowchart

• Example 1. This is an algorithm that decides whether a student should receive


a distinction.

READ grade
IF (grade >= 95)
THEN student receives a distinction
• This is the simplest case of selection control. In fact, in essence it is a
sequential form but the second step is only taken when the condition
contained in the brackets is true, that is the last step (starting at THEN) is
selected for execution only when the condition is satisfied.
• Example 2. Control access to a computer depending on whether the user has
supplied a username and password that are contained in the system
database.
IF (username in database AND password corresponds to user)
THEN Accept user
ELSE
Deny user

• In this case, there is also a decision to be made but a more complex one. In
the condition is true only the Accept user step is executed and if the condition
is false only the Deny user step is executed.
• That is, the condition helps us make a selection which controls which of the
two steps will be executed.
• Now look more closely to the condition. Does it guarantees that the user is
valid? What if we had this condition instead, which looks pretty similar: IF
(username in database AND password in database)?
• What would happen if somebody typed a valid username but the password
of a different but also valid user?
• Does this second condition satisfies our requirement that to access this
account one should be the right user and know the corresponding password?
• When you write a condition always make sure that it performs exactly the
check that you intended it to! It is very easy to translate words in
pseudocode that does a different thing than what was intended!
Example 3. Decide on a student’s grade based on their coursework mark.

READ result
CASE (result >=90)
PRINT ‘A’
CASE (result >=80)
PRINT ‘B’
CASE (result >=70)
PRINT ‘C’
CASE (result >=60)
PRINT ‘D’
CASE (result <60)
PRINT ‘F’
• In example 3, there are five conditions which are checked, one after the other.

• Question. What is the difference between examples 1, and 2, and 3?

• Answer. There are three differences:

• Example 1 provides no alternative action is the condition is not true.


• Example 2 provides an alternative action when the conditions are false.
• Example 3 provides multiple alternatives to select from.
• Repetition.

• In Repetition one or more steps are performed repeatedly.


• Another action often required in data processing is looping, i.e. Repeating the
same set of operations for two or more occurrences of data.

• Example: Design an algorithm to find the sum of all integers between 1 and
10,000 inclusive. Draw a flowchart to depict your algorithm.
• Algorithm
Step 1 Set sum = 0
Step 2 Set number = 0
Step 3 Set sum = sum + number
Step 4 Set number = number + 1
Step 5 If number < 10001 then go to step 3 else go to step 6
Step 6 Print sum
Step 7 Stop
• Flowchart
• Example 1. Compute the average of ten numbers:

total = 0
average = 0
FOR 1 to 10
Read number
total = total + number
ENDFOR
average = total / 10
• Example 2. Read numbers and add them up until their total value reaches (or
exceeds) a set value represented by S.

WHILE (total < S) DO


Read number
total = total + number
ENDDO

Question. What is the difference between Examples 1, and 2?


• Answer. The difference is that in Example 1 we know beforehand the exact
number of repetitions that will be carried out (they are 10), but in
• Example 2 we do not know beforehand (it depends on the particular
numbers that will be fed to our program during its execution).
• Sequence, selection, and repetition are by themselves simple.
• But put together, they can construct any algorithm that we can imagine.
• One can imagine a situation involving several decisions.
• This is illustrated in the example given below.
if condition 1 is true
then test condition 2
if condition 2 is true
then perform step A
otherwise perform step B
otherwise, perform step C
stop
• Flowchart


• The Concept of Algorithm
• One of the basic concepts of mathematics and computer science is algorithm.
• By an algorithm is meant a list of instructions specifying a sequence of
operations which will give the answer to any problem of a given type.
• In mathematics, a class of problems is considered solved when an algorithm
for solving them is found.
• The discovery of such algorithms is a natural aim of mathematics and
computer science.
• The concept of algorithm is very germane to the study of Computer Science.
• Computational problems are solvable only if there exist algorithms for solving
them.
• Characteristics of Algorithm
• It should be deterministic:
• An algorithm must be given in the form of a finite list of instructions
giving the exact procedure to be followed at each step of the calculation.
Thus the calculation does not depend on the calculator.; it is a deterministic
process which can be repeated successfully at any time and by anyone. So it
should not be ambiguous.

• . It should be general:
• An algorithm is a single list of instructions defining a calculation which
may be carried out on any initial data and which in each case gives the
correct result. In other words, an algorithm tells how to solve not just one
particular problem, but a whole class of similar problems.
• . It should be finite:
• Although the algorithm has definite length, its execution may repeat some
steps indefinitely that is, the computation may not terminate. In particular,
non-termination may occur for some input data. For example, an algorithm to
compute all the digits of the square root of x would terminate for x = 4, and
not terminate for x=3. To be accepted, an algorithm must terminate for all the
inputs.

• It should have one entry and exit: Multiple entries or exits may make the
algorithm ambiguous.
• It should act at least on one input and it should produce at least one output.
• DECISION TABLES
• A decision table, just like a flowchart is a tool of programming and systems
analysis. It can be used to define complex program logic.
Decision Table Format

• The table is divided into four major parts;


• The table is divided into four major parts;
I Condition Stub
II Condition entries
III Action Stub
IV Action entries.
• Apart from these, there is also a portion reserved for table heading and
another for decision rules.
• The condition stub will contain the conditions to be tested while the action
stub will contain actions to be taken after the examination of each rule.
• The rule itself is a combination of answers to the questions asked in the
conditions stub. If three conditions are entered in the condition stub, then
we will expect 8 rules i.e. 23.
• In general, if there are n conditions, there will be 2n rules.
• However, some of the rules may be irrelevant or redundant and hence such
rules are simply ignored. Realistically speaking then there will always be less
than or equal to 2n rules for n conditions.
• The condition entries are responses to the questions asked under the
conditions stub and they are usually answered as a “YES” or a “NO”.
• The action entries contain column by column, the action actually taken in
response to the rule in the column. X is put against each action taken in
response to a rule.
• ARRAY
• An array is a set of data items all of the same type and stored together in the
memory.
• All the data in an array can therefore be referred to, by a single identifier. The
number of data items in any array is fixed.
• Each array element can be referenced by use of a subscripted variable. An
array can be one-dimensional or multi-dimensional.
• A classic mathematical notation provides the way for naming both an array
and its individual elements.
• The identifier or variable ITEM, for instance can stand for the array of items in
a warehouse while
• ITEM(1), ITEM (2), ITEM (3), .....
• represent the first, second, third and other individual items in that array.
• ITEM(1), ITEM (2), ITEM (3), .....
• represent the first, second, third and other individual items in that array.
ITEM

• This is a linear array ITEM

• A two-dimensional array however is made up of rows and columns of data.


• A two-dimensional array of four rows and three columns can be depicted as
shown below
TABLE

A 2-dimensional array TABLE

• A multi-dimensional array is specified by giving more than a pair of


dimensional limits in the description of the array.
• Exercises

1. Write an algorithm to sort 10 numbers in increasing order


2. given a positive integer, write and algorithm to determine that it is a
prime number?
PROBLEM SOLVING
(COS102)

COMPILED BY DR.ADEPEGBA AND MR. ERINFOLAMI


INTRODUCTION TO CORE CONCEPT OF COMPUTING

• A computer is a machine that can be programmed to carry out sequences of arithmetic


or logical operations (computation) automatically. The importance of it is to make human
work fast and easy to do.
• Computer science is the study of the theoretical foundations of information and
computation , and of practical techniques for their implementation and application in
computer systems.
• Program is a set of instruction given to a computer to perform a particular task.
INTRODUCTION TO CORE CONCEPT OF COMPUTING

• Programming is the act of writing programs.


• Programming language is a language the computer understands that is use to pass
instructions to it by a computer programmer.
INTRODUCTION TO CORE CONCEPT OF COMPUTING

Types of programming languages


• Structural Programming languages e.g C , Fortran, Pascal, Cobol , Basic
• Object-oriented Programming languages e.g JAVA, C++, C#
• Functional Programming languages
• Logic Programming languages
INTRODUCTION TO CORE CONCEPT OF COMPUTING

Computer sciences accreditation Board (CSAB) identifies four general areas that
it considers crucial to the discipline of computer science :
• Theory of Computation
Investigates how specific computational problems can be solved efficiently.
• Algorithms and Data Structures
Investigates efficient ways to storing , organizing and using data.
INTRODUCTION TO CORE CONCEPT OF COMPUTING
(CONTINUATION)

• Programming methodology and languages


Investigates different approach to describing and expressing problem solutions.
• Computer elements and architecture
Investigates the design and operation of computer systems.
INTRODUCTION TO CORE CONCEPT OF COMPUTING

• Computing is the process of giving the computer some tasks to do related to what it has
been programmed to do. They are majorly arithmetic operations.
COMPUTATIONAL PROBLEM OR PROBLEM

• In theoretical computer science, a computational problem is a problem that may be


solved by an algorithm. E.g problem of factoring “Given a positive integer n , find a
nontrivial prime factor of n”.
TYPES OF COMPUTATIONAL PROBLEMS

• Decision problem
• Search problem
• Counting problem
• Optimization problem
• Function problem
PROBLEM SOLVING

• Problem solving is the sequential process of analyzing information related


to a given situation and generating appropriate response options.
Six steps to solving a problem
• Understand the Problem
• Formulate a Model
• Develop an Algorithm
• Write the Program
PROBLEM SOLVING

• Test the Program


• Evaluate the Solution
PROBLEM SOLVING (CONTD)

• Step1: understand the problem


It sound strange, but the first step to solving any problem is to make sure that you
understand the problem that you are trying to solve.
What input data/information is available?
What does it represent?
What format is it in?
Is anything missing ?
PROBLEM SOLVING (CONTD)

Do I have everything that I need?


What output information am i trying to produce?
What do I want the result to look like …text, a picture, a graph …?
What am I going to have to compute ?
PROBLEM SOLVING

• Step2: Formulate a model


Now we need to understand the processing part of the problem. Many problems break
down into smaller problems that require some kind of simple mathematical computations
in order to process the data.
• Step3: Develop an Algorithm
Algorithm is a step by step instruction to solving a problem or computational problem.
PROBLEM SOLVING

• To develop an algorithm , we need to represent the instructions in some way that is


understandable to a person who is trying to figure out the steps involved two commonly
used representation for algorithm is by using : pseudocode and flow charts.
• pseudocode : Is a simple and concise sequence of English-like instructions to solve a
problem.
• Flow charts: Is a diagrammatic representation of an algorithm
PROBLEM SOLVING

• WRITING PROGRAM
algorithm for finding the average of a set of grades and the program

Pseudocode Processing code (i.e., program)


set the sum of the grade values to 0. int sum = 0;

load all grades x1 … xn from file. byte[] x = loadBytes("numbers");


repeat n times { for (int i=0; i<x.length; i++)

get grade xi add Xi to the sum sum = sum + x[i];


PROBLEM SOLVING

} int avg = sum / x.length;

compute the average to be sum / n. print(avg);


print the average.
PROBLEM SOLVING

• Compiling is the process of converting a program into instructions that can be


understood by the computer.
PROBLEM SOLVING

• Test the program: this is the process you look at output of coding on the computer if is
giving you the desired output.
• Running a program is the process of telling the computer to evaluate the compiled
instructions.
• Bugs are problems/errors with a program that cause it to stop working or produce
incorrect or undesirable results.
• The process of finding and fixing errors in your code is called debugging
EXAMPLE OF PROBLEM SOLVED WITH ALGORITHM

• Solving the problem of a broken lamp.


Solution
Pseudocode
• If lamp works , go to step 7
• Check if lamp is plugged in
• If not plugged in, plug in lamp
• Check if bulb is burnt out
EXAMPLE OF PROBLEM SOLVED WITH ALGORITHM

• If bulb is burnt, replace bulb


• If lamp doesn’t work buy new lamp
• Quit. Problem solved
FLOWCHART
FLOWCHART

• What Is a Flowchart?
A flowchart is a diagram that visually represents the progression of steps of a process or
workflows. They are commonly used as decision-making, problem-solving, system designing,
and educational tools.
There are multiple types of flowcharts including;
• Process flowchart - shows the steps of a process in sequential order
• Workflow chart - visualizes a workflow or actions that need to be carried out to achieve
a goal
FLOWCHART

• Data flow chart - represents how data is processed within a system


• Swim lane flowchart - illustrates process steps along with responsible owners or
departments
FLOWCHART

• Flowchart Symbols; Listed below are some of most common flowchart symbols and their
meanings.
FLOWCHART
FLOWCHART MEANINGS

• Terminal - Shows the start or the end of the process.


• Process - Process is shown as a rectangle
• Decision - Shown as a diamond and usually has a question on it.
• Data - Typically shown as a slanted rectangle, this shows any input or output from the
process.
• Swimlanes - Although not a flowchart symbol, swimlanes are useful to differentiate or
highlight the ownership of the processes.
• Document - To highlight if the a document is generated throughout the process.
FLOWCHART
SYMBOLS IN FLOWCHART
SYMBOLS IN FLOWCHART
SYMBOLS IN FLOWCHART
SYMBOLS IN FLOWCHART
SYMBOLS IN FLOWCHART
HOW TO CREATE A FLOWCHART

• Identify the process or the workflow you and your team want to document or visualize.
• Identify the different steps involved in executing this process. If several people are responsible
for carrying out the process, collaborate and get their input for an accurate visualization.
• Using the standard flowchart symbols available in the Creately flowchart maker, convert the
listed steps into a flowchart.
• First drag and drop the Start/End symbol onto the canvas. Using the Plus Create option, add
the next symbol depending on whether it’s a process/ step/ operation or decision. Make sure
to use the correct flowchart symbol to represent your data.
HOW TO CREATE A FLOWCHART

• Connect the shapes with arrows highlighting the flow of the process or workflow.
Creately’s Plus Create automatically recognizes the flow and adds the relevant connector
as you draw the flowchart.
• Customize the flowchart as necessary with Creately’s preset color themes before sharing
it with stakeholders for feedback.
• Review the flowchart frequently and update it as the process it represents, undergoes
changes.
ASSIGNMENT

• 1.(a) . Draw a flowchart to compute the breadth of a rectangle of a given area.


(b) Write an Algorithm to compute the area of a rectangle.
• 2. The following instructions gives the steps to be followed for making and drinking a
glass of orange squash. The instructions are to be arranged accordingly and to be filled in
appropriate flowchart symbols. Draw the flowchart by filling in the instruction inside
correct boxes.
ASSIGNMENT(CONTD)

i. Start
ii. Pour measure of juice into glass
iii. Take juice out of the cupboard
iv. drink juice
v. Take the glass orange squash out of the fridge to serve
vi. fill up glass to top with water
vii. Refrigerate to chill
viii. End/stop
EXAMPLE

• Consumption of a drink:
1. get off couch
2. walk to kitchen
3. open refrigerator
4. if there is a carton of lemonade or orange juice then {
ALGORITHM

1. take the carton


2. close refrigerator
3. go to the cupboard
4. open cupboard
5. take a glass
6. close cupboard
7. pour lemonade or juice into glass
8. go to refrigerator
9. open refrigerator
10. put carton in refrigerator
11. close refrigerator
• }
ALGORITHM (CONTD)

1. otherwise if there is a soda then {


2. take soda
3. close refrigerator
4. open soda
• }
1. drink it
EXAMPLE 2

This is an algorithm that decides whether a student should receive a distinction.


READ grade
IF (grade >= 70)
THEN student receives a distinction
EXAMPLE3

• Example 3. Decide on a student’s grade based on their coursework mark.


READ result
CASE (result >=90)
PRINT ‘A’
CASE (result >=80)
EXAMPLE 3(CONTD)

PRINT ‘B’
CASE (result >=70)
PRINT ‘C’
CASE (result >=60)
PRINT ‘D’
CASE (result < 60)
PRINT ‘F’
In this case, there are five conditions which are checked, one after the other.
CONTROL STRUCTURES FOR PSEUDOCODE

• Sequence: listing instructions step by step in order(often numbered)

• Condition: making a decision and doing one thing or somethingelse depending on the
outcome of the decision.

• Repetition : repeating something a fixed number of times or until some condition occurs.
CONTROL STRUCTURES FOR PSEUDOCODE
(CONTD)
• Storage: storing information for use in instructions further down the list.

• Jumping: being able to jump to a specific step when needed


ABSTRACTION

• Abstraction is the process of reducing or factoring out details that are not necessary in
order to describe an algorithm.

• The key concept of abstraction is sub-algorithm or sub-program.

• Sub-algorithm or Sub-program is an algorithm written at a particular place to solve a


particular problem , such that you can make use of it later with another algorithm to
solve a related problem.
EXAMPLE OF A SUB-ALGORITHM

• AlgorithmX: QuenchThirst
1. get off couch
2. walk to kitchen
3. open refrigerator
4. perform SubAlgorithm1
5. close refrigerator
6. drink it
EXAMPLE OF A SUB-ALGORITHM (CONTD)

SubAlgorithm1: GetDrink
1. if there is a carton of lemonade or orange juice then {

2. take the carton

3. close refrigerator
4. go to the cupboard
5. open cupboard

6. take a glass

7. close cupboard
EXAMPLE OF A SUB-ALGORITHM (CONTD)

1. pour lemonade or juice into glass


2. go to refrigerator
3. open refrigerator
4. put carton in refrigerator
• }otherwise if there is a soda then {
1. take soda
2. open soda
• }
SUB-ALGORITHM IN PROGRAMMING

• Sub-algorithm are called several names in programming e.g functions, modules.


• In JavaScript programming language sub-algorithms are called functions.
• In PHP sub-algorithms are called functions.
• In ReactJS and React native sub-algorithms are called components.
• In AngularJS sub-algorithms are called widgets.
EXAMPLES OF SOME MEANINGFUL SUB-
ALGORITHM
• SubAlgorithm1:chooseDrink() or chooseDrinkFromRefrigerator()
• SubAlgorithm2:pourDrink() or pourCartonDrink()
• SubAlgorithm3:getGlass() or getGlassFromCupboard()
• SubAlgorithm4:getPlate() or getPlateFromCupboard()
• SubAlgorithm5:getUtensils() or getForkAndKnife() or getUtensilsFromDrawer()
USE OF SUB-ALGORITHM

• AlgorithmX: QuenchThirst
• 1. get off couch
• 2. walk to kitchen
• 3. chooseDrink()
• 4. drink it
USE OF SUB-ALGORITHM

• Algorithm Y: SetTablefor4
1.Walk to kitchen
2. Repeat 4 times {
3. getGlass()
4. Place glass on table
5. getplate()
6. Place plate on table
7. getutensils()
8. Place knife and fork on table
}
PARAMETER

• Parameters are details required for a function to run. And a function is also known as
sub-algorithm.
USING PARAMETER IN FUNCTION

• GetGlasses(n):
• 1. go to the cupboard
• 2. open cupboard
• 3. repeat n times {
• 4. take a glass
• }
• 5. close cupboard
USING PARAMETER IN FUNCTION

• The n in the function above signify that there’s a parameter along the function that has to
be provided.

• Values of parameters are always numbers.

• Instruction number four will be repeated the numbers of time the value of n is.
ALGORITHM EFFICIENCY

• Algorithm efficiency simply means how good an algorithm is or how efficient an


algorithm is. This can be measured base on two conditions which are time complexity
and space complexity respectively.

• Time complexity simply means how long it takes a computer to run an algorithm.

• Space complexity simply means how much space the computer use while running an
algorithm.
COS 102
PROGRAMMING
Program
• A program is a list of instructions that the computer must follow to
process data into information.
• The instructions consist of statements used in a programming language,
such as BASIC.
• Programming is a five-step process for creating that list of instructions.
• The five steps in the programming process are as follows:
1. Clarify/define the problem—include needed output, input, processing
requirements.
2. Design a solution—use modeling tools to chart the program.
3. Code the program—use a programming language’s syntax, or rules, to
write the program.
4. Test the program—get rid of any logic errors, or “bugs,” in the program
(“debug” it).
5. Document and maintain the program—include written instructions for users,
explanation of the program, and operating instructions.
1. The problem clarification (definition) step consists of six mini-steps—
a. clarifying program objectives and users,
b. outputs,
c. inputs,
d. processing tasks;
e. studying the feasibility of the program; and
f. documenting the analysis.
a. clarifying program objectives and users,
• You need to write a statement of the objectives you are trying to
accomplish— the problem you are trying to solve.
• You also need to make sure you know who the users of the program
b. clarify desired outputs
• you need to understand the outputs—
• what to get out of the system—before you specify the inputs.
• what kind of hardcopy is wanted
• What information should the outputs include
c. Clarify desired inputs
• Once you know the kind of outputs required, you can then think about
input.
• What kind of input data is needed
• In what form should it appear
• What is its source
d. Clarify the desired processing
you need to understand the processing tasks that must occur in order for
input data to be processed into output data.
e. double-check the feasibility of implementing the program
Is the kind of program feasible within the present budget?
Will it take too long to accomplish
f. document the analysis
• This includes writing objective specifications of the entire process being
described.
2. Design the Program
• design the solution specified by the systems analysts
• you first need to create an algorithm.
• In computer programming, there are different algorithms to accomplish any
given task, and
• each algorithm has specific advantages and disadvantages in different
situations.
• Inventing elegant algorithms—algorithms that are simple and require the
fewest steps possible—is one of the principal challenges in programming.
• most programmers use a design approach called structured programming.
• Structured programming takes a top-down approach that breaks programs
into modular forms. (sequence, selection, case, and iteration).
a. determine the program logic, using a top-down approach
• The top-down program design is used to identify the program’s processing
steps, or modules.
• After the program is designed, the actual coding proceeds from the bottom
up, using the modular approach.
• Modularization: The concept of modularization is important. Modularization
dramatically simplifies program development, because each part can be
developed and tested separately.
• A module is a processing step of a program.
• Each module is made up of logically related program statements.
Sometimes called a subprogram or subroutine.
• Top-down program design: Top-down program design can be represented
graphically in a hierarchy chart.
• A hierarchy chart, or structure chart, illustrates the overall purpose of the
program, by identifying all the modules needed to achieve that purpose
and the relationships among them.
• The program move in sequence from one module to the next until all have
been processed.
• There must be three principal modules corresponding to the three principal
computing operations—input, processing, and output.
b. DESIGN DETAILS, USING PSEUDOCODE AND/OR FLOWCHARTS
• There are two ways to show details—write them or draw them; that is, use
pseudocode or use flowcharts. Most projects use both methods.
• Pseudocode is a method of designing a program using normal human-
language statements to describe the logic and the processing flow.
• A program flowchart is a chart that graphically presents the detailed series of
steps (algorithm, or logical flow) needed to solve a programming problem.
• The flowchart uses standard symbols—called ANSI symbols, after the
American National Standards Institute, which developed them.
• Control structures: A control structure, or logic structure, is a structure that
controls the logical sequence in which computer program instructions are
executed.
• In structured program design, three control structures are used to form the
logic of a program: sequence, selection, and iteration (or loop).
• One thing that all three control structures have in common is one entry and
one exit.
• The control structure is entered at a single point and exited at another single
point. This helps to avoid incomprehensible program known as spaghetti
code.

The three control structures:


• Sequence control structure:
• In the sequence control structure, one program statement follows another in
logical order.
• There are no decisions to make, no choices between “yes” or “no.”
• They logically follow one another in sequential order.
• One program statement logically follow one another in sequential order.

Some practical examples


• Reading input from devices, such as keyboards or sensors
• Performing arithmetic operations and calculations
• Printing data to a screen or file
• Calling functions to execute specific tasks
• Selection control structure:
• The selection control structure —also known as an IF-THEN-ELSE structure —
represents a choice.
• It offers two paths to follow when a decision must be made by a program.
• A variation on the usual selection control structure is the case control
structure.
• This offers more than a single yes-or-no decision.
• The case structure allows several alternatives, or “cases,” to be presented.
(“IFCase 1 occurs, THEN do thus-and-so. IF Case 2 occurs, THEN follow an
alternative course. . . .” And so on.)
• The case control structure saves the programmer the trouble of having to
indicate a lot of separate IF-THEN-ELSE conditions.
• Selection control structure (IF-THEN-ELSE).
• Variation on selection: the case control structure
• (more than a single yes-or-no decision)
• Iteration control structure: In the iteration, or loop, control structure, a
process may be repeated as long as a certain condition remains true.
• There are two types of iteration structures—DO UNTIL and DO WHILE.
• If several statements need to be repeated, you must decide when to stop
repeating them.
• You can decide to stop them at the beginning of the loop, using the DO
WHILE structure.
• Or you can decide to stop them at the end of the loop, using the DO UNTIL
structure.
• The DO UNTIL iteration means that the loop statements will be executed at
least once, because in this case the iteration statements are executed before
the program checks whether to stop.
• There are two types of iteration structures—DO UNTIL and DO WHILE
3. Code the Program
• Coding consists of translating the logic requirements from pseudocode or
flowcharts into a programming language
• SELECT THE APPROPRIATE HIGH-LEVEL PROGRAMMING LANGUAGE
• CODE THE PROGRAM IN THAT LANGUAGE, FOLLOWING THE SYNTAX

4. Test the Program


• Program testing involves running various tests and then running real world
data to make sure the program works.
• Two principal activities are desk-checking and debugging. These steps are
called alpha testing.
• To debug means to detect, locate, and remove all errors in a computer
program.
• Mistakes may be syntax errors or logic errors.
• Syntax errors are caused by typographical errors and incorrect use of the
programming language.
• Logic errors are caused by incorrect use of control structures.
• Programs called diagnostics exist to check program syntax and display
syntax-error messages.
• Diagnostic programs thus help identify and solve problems.
• Sometimes debugging is partially done in the third step, program coding,
using the “buddy system.”
• In this system, two people sit side by side; while one person (the “driver”)
codes, the other person (the “navigator”) checks the code, corrects it, and
offers suggestions for improvement.
• RUN REAL-WORLD DATA
• After desk-checking and debugging, the program may run fine—in the
laboratory. However, it needs to be tested with real data; this is called beta
testing.
• it is even advisable to test the program with bad data—data that is faulty,
incomplete, or in overwhelming quantities—to see if you can make the
system crash.
• 5. Document & Maintain the Program
• Writing the program documentation is the fifth step in programming.
• The resulting documentation consists of written descriptions of what a
program is and how to use it.
• Documentation is not just an end-stage process of programming.
• It has been (or should have been) going on throughout all programming
steps.
• Documentation is needed for people who will be using or be involved with
the program in the future.
• Documentation should be prepared for several different kinds of readers—
users, operators, and programmers.
USER DOCUMENTATION
• When you buy a commercial software package, such as a spreadsheet, you
normally get a manual with it.
• This is user documentation. Nowadays manuals are usually on the software
CD.
OPERATOR DOCUMENTATION
• The people who run large computers are called computer operators.
Because they are not always programmers, they need to be told what to do
when the program malfunctions.
• The operator documentation gives them this information.
• PROGRAMMER DOCUMENTATION
• Long after the original programming team has disbanded, the program may
still be in use.
• If, as is often the case, a fifth of the programming staff leaves every year, after
5 years there could be a whole new bunch of programmers who know
nothing about the software.
• Program documentation helps train these newcomers and enables them to
maintain the existing system.

You might also like