Algorithm__updated_slides (1)
Algorithm__updated_slides (1)
For example, the following formula describes the relationship between temperatures in the Celsius and
Fahrenheit scales:
5(F−32)=9C
where
The formula defines the relationship between temperatures in Celsius and Fahrenheit, but it doesn't give
us an explicit algorithm for converting from one to the other. Fortunately, if we have some understanding
of algebra, we can easily write such an algorithm.
First, we can use the basic operations of algebra to convert the previous formula into this form: 2
C = 5(F – 32) /9
What are algorithms?
Example 1
Working from this formula, it's a relatively straightforward task to write an algorithm to convert from Fahrenheit to Celsius:
Note that we've shifted from describing the relationship between the two scales to listing computational steps in a specific
order.
3
What are algorithms?
1. Start.
2. Read r: radius value as the input given by the user.
3. Calculate the Area: 3.14 * r * r.
4. Display the Area.
5. End.
4
What are algorithms?
◼ An algorithm is a sequence of finite instructions, often used for calculation and data processing.
◼ It is formally a type of effective method in which a list of well-defined instructions for completing a
task will, when given an initial state, proceed through a well-defined series of successive
states,eventually terminating in an end-state.
5
Characteristics of an algorithm
source: https://www.geeksforgeeks.org/introduction-to-algorithms/
What do algorithms have to do with programming?
Computer programming primarily involves creating clear, step-by-step procedures, or algorithms, for a computer to follow
in order to achieve specific results. While computers excel at calculations and memory, they are incapable of applying
these abilities to practical problems without human guidance. Tasks like calculating a sine or logarithm may be simple for
a computer, but solving more complex problems, such as graphing functions or performing real-world calculations,
requires algorithms written by programmers to "teach" the computer how to complete them.
Example: plot the graph of y = sin x on the screen, or balance your checkbook, or compute the area of the region
bounded by 1 ≤ x ≤ 100 and 0 ≤ y ≤ 1/ x, the computer is helpless until someone writes algorithms to accomplish these
tasks, and “teaches” them to the computer.
7
How to specify an algorithm?
Pseudocode and flowchart are the two options that are most widely used
nowadays for specifying algorithms.
Natural language
It is very simple and easy to specify an algorithm using natural language. But many times, specification
of algorithm by using natural language is not clear and thereby we get brief specification.
Example: An algorithm to perform addition of two numbers.
Step 1: Read the first number, say a.
Step 2: Read the first number, say b.
Step 3: Add the above two numbers and store the result in c.
Step 4: Display the result from c.
Such a specification creates difficulty while implementing it. Hence many programmers prefer
specification of algorithm by means of Pseudocode.
9
Flowchart
In the earlier days of computing, the dominant method for specifying algorithms was a
flowchart, this representation technique has proved to be inconvenient. Flowchart is a
graphical representation of an algorithm. It is a method of expressing an algorithm by a
collection of connected geometric shapes containing descriptions of the algorithm's steps.
10
Pseudocode
What is pseudocode?
Pseudocode is a valuable tool for outlining the logic of a program before it's written or for documenting it after the fact. It
resembles programming code but isn’t directly executable. Pseudocode can express anything from high-level program
logic to detailed functions and methods. However, there’s no standard format or vocabulary for pseudocode, and its
structure can vary greatly, ranging from formal prose to something closely resembling actual code. Despite this flexibility,
pseudocode helps in clearly articulating algorithms for programmers, even those unfamiliar with the specific logic.
Use of pseudocode:
◼ Simplify logic of a program
◼ communicate easily with programmers
◼ Save time and prevent mistakes
11
Difference between Algorithm and Pseudocode:
An algorithm is a well defined sequence of instructions that provide a solution to the given
problem.
A pseudocode is a method which is used to represent an algorithm.
An algorithm has some specific characteristics that describe the process.
A pseudocode on the other hand is not restricted to something. It’s only objective is to represent
an algorithm in a realistic manner.
12
Pseudocode
Ultimately, the most important characteristic of pseudocode is not really what it is, but what
it makes possible. As noted above, when we start with well-written pseudocode, virtually
any programmer with reasonable competence in a given programming language should
be able to implement the algorithm described by the pseudocode, in the given language,
with little or no need for further instruction.
Pseudocode is made up of the following logics structures that have been proved to be
sufficient for writing any computer program:
◼ Séquence Logic
◼ Selection Logic
◼ Iteration Logic
13
Pseudocode
Sequence Logic
It is used to perform instruction in a sequence, which is one after another.
Thus, for sequence logic instructions pseudocode are writing in an order in which they are to be performed
The logic flow of pseudocode are from top to bottom.
14
Pseudocode
Selection Logic
It is used for making decision and for selecting the proper path out of two or more alternative in program logic.
It is also known as decision logic.
Selection logic is depicted as either IF……THEN or IF…… THEN ELSE structure
15
Pseudocode
Iteration logic
It is used to produce loops when one or more instruction may be
executed several times depending on some the conditions
It used structure called DO…WHILE, FOR, REPEAT…UNTIL
16
Pseudocode
17
Pseudocode
1. An algorithm is a procedure. It has two parts; the first part is head and the second part is
body.
2. The Head section consists of keyword Algorithm and Name of the algorithm with
parameter list.
E.g. Algorithm name1(p1, p2,...,pn)
The head section also has the following:
//Problem Description:
//Input:
//Output:
3. In the body of an algorithm various programming constructs like if, for, while and some
statements like assignments are used.
4. The compound statements may be enclosed with { and \ brackets. if, for, while can be
open and closed by {, } respectively.
Proper indentation is must for block. 18
19
Input and output in an algorithm
◼ Input
Given a task, the questions to ask yourself to identify the right input are:
◼ Output
21
Rule for writing pseudocode
2. Use the braces for indentation. Indentation should be use for avery code block
3. indent the statements that fall inside the loop, but not the keywords that form the loop
Sequence Logic
It refers to the order of operations or steps that are followed in a precise and linear
manner, where each step is executed one after the other.
It's an essential part of algorithm design and programming because it ensures that
instructions are carried out in a specific and predictable order, leading to the correct
outcome.
In sequence logic, the steps are performed sequentially, meaning there is no iteration
(looping) or conditional branching (like in IF statements). Each action follows the previous
one in a simple, straight path.
Sequence Logic
Example: calculate the area of a circle given its radius rr, where the formula is A=π*r^2 A=π*r^2
Algorithm calcul_area_cycle(r):
{
1. Input: Read the radius rr.
//set the value of pi in a variable
2. Compute: Calculate the area called p
using the formula area=π*r^2 p:=3.14
A=π*r^2. //Calculate the area and assign it to
3. Output: Display the area area. //variable called area
area:=p*r*r
write(area)
return area
}
Sequence Logic
ALGORITHM Sum
{
ALGORITHM Sum a=read(‘give the values of a’)
{ b=read(‘give the values of b’)
//This algorithm performs addition of two
//numbers //This algorithm performs //addition
//Input: Two integers a and b
of two numbers
//Output: Addition of two integers
//Input: Two integers a and b
c:=a+b //Output: Addition of two integers
return c c:=a+b
} write(c)
return c
}
Sequence Logic
Exercise1:Given the principal PP, rate of interest RR, and time TT, calculate the simple interest using
the formula:
(PxRxT)/100
Exercise 2: Given a temperature in Celsius CC, convert it to Fahrenheit FF using the formula:
F=(9/5)C+32
Selection logic
It is a control structure in programming and algorithms that allows decisions to be made
based on certain conditions. It involves choosing one of several possible actions
depending on whether a condition is true or false. This decision-making process is
typically implemented using conditional statements, such as IF, ELSE.
Selection logic helps control the flow of an algorithm by allowing it to branch in different
directions, based on logical tests. This logic is essential for algorithms that require different
outcomes or actions depending on varying inputs or conditions.
Selection Logic
Key Concepts of Selection Logic:
1. Conditions:
○ Conditions are logical expressions that evaluate to either True or False (e.g., x
> 10, a == b).
2. Branching:
○ Based on the result of a condition, the program can "branch" into different paths.
If a condition is true, one block of code is executed; otherwise, another block
may be executed.
3. Control Statements:
○ The most common selection logic structures are IF, IF-ELSE, and ELSE-IF
statements.
○ They allow different sets of instructions to be executed depending on the
evaluation of conditions.
Selection Logic
IF condition
{
Sum 3 numbers and print the result if it’s greater
instructions
than 10.
}
Algao som(a,b,c)
{
s=a+b+c
IF s>10{
write(s)
}
}
Iteration Logic
Exercise 3: Given a sequence of numbers, write an algorithm to compute the Sum of Elements.
1. What is the input?
2. What is the output?
3. write the pseudocode
Iteration Logic
Iteration logic refers to the process of repeating a set of logical steps or operations until a particular
condition is met. In algorithmic terms, logical iteration often involves loops, where a block of instructions
is executed repeatedly, typically under a specific logical condition. This type of iteration is fundamental to
problem-solving in both mathematics and computer science.
Key Elements of Logical Iteration:
Initialization:
● Before starting the iteration, initialize the variables or values that will be used in the loop.
Condition:
● A logical condition is evaluated before (or during) each iteration. The iteration continues as long as
this condition remains true.
Update:
● Variables or states are updated in each iteration to move closer to satisfying the termination
condition.
Termination:
A FOR loop is used when the number of iterations is predetermined. It's often used for
tasks like counting, iterating through lists, or processing arrays.
FOR(initialization; condition; update):
{
execute this block of code
}
We use a while loop when we do not know how many times to loop
The first time the while statement is encountered, the condition is tested, and if it is true, all the statements in the body of
the loop are run. Then the condition is tested again. If it is still true, then the body of the loop is run again and so on until
the condition become false. Say we were making a searching algorithm, we would want the loop to continue until we
found the thing we were looking for, so we would use a while loop!
Let's say we were making a searching algorithm. We would want to search the list until we found the element we were
looking for}
statement
statement
[ more statements ... ]
}
Iteration Logic: WHILE
Example 1: Counting down from N to 1 Example 2:
Write an algorithm that compute the
Algo count_down{ factorial of number N.
WRITE N
Algo Factorial{
READ N
This means that while we do not know how many times to loop something, we can just use a Do While
loop.
Algo DOwhile{
DO {
instructions
WHILE condition
}
Iteration Logic: DO WHILE
Example1:
Use a DO ... WHILE loop to calculate the sum of all even numbers between 1 and 20.
Algo sum1_20 {
s=0
i=1
Do{
s=s+i
}
WHILE i <=20
}
Iteration Logic: REPEAT UNTIL
A repeat until loop is a logical iteration statement used in algorithm that repeatedly executes a block of
code until a specified condition evaluates to true.
Algo repeat_until{
REPEAT{
instruction
}
UNTIL condition
}
Iteration Logic: REPEAT UNTIL
Algo sum1_5 {
count = 0
REPEAT{
count = count + 1
}
UNTIL count >= 5
}
TITLE
THANKS!
9/12/2021 39