0% found this document useful (0 votes)
28 views54 pages

Section 4 Algorithmic Thinking

This document discusses algorithmic thinking and provides examples of flowcharts and conditional statements. It defines algorithmic thinking as the ability to identify and analyze problems and develop step-by-step procedures to solve them. Flowcharts are presented as a way to represent algorithms graphically using different blocks like start, process, conditional, and input/output. Conditional statements like if, if-else, and if-elseif-else are discussed along with logical and relational operators. Loops are also introduced.

Uploaded by

narimanemeradsa
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)
28 views54 pages

Section 4 Algorithmic Thinking

This document discusses algorithmic thinking and provides examples of flowcharts and conditional statements. It defines algorithmic thinking as the ability to identify and analyze problems and develop step-by-step procedures to solve them. Flowcharts are presented as a way to represent algorithms graphically using different blocks like start, process, conditional, and input/output. Conditional statements like if, if-else, and if-elseif-else are discussed along with logical and relational operators. Loops are also introduced.

Uploaded by

narimanemeradsa
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/ 54

SECTION 4:

ALGORITHMIC THINKING
ENGR 112 – Introduction to Engineering Computing
2 Algorithmic Thinking

K. Webb ENGR 112


Algorithmic Thinking
3

 Algorithmic thinking:
 The ability to identify and analyze problems, and to
develop and refine algorithms for the solution of those
problems
 Algorithm:
 Detailed step-by-step procedure for the performance of
a task
 Learning to program is about developing
algorithmic thinking skills, not about learning a
programming language

K. Webb ENGR 112


Algorithms
4

 Ultimately, algorithms will be implemented by


writing code in a particular programming language
 Algorithm design is (mostly) language-independent
A procedure that can be implemented in any language

 Universal algorithm representations:


 Flowcharts
 Graphical representation

 Pseudocode
 Natural language
 Not necessarily language-independent
K. Webb ENGR 112
5 Flowcharts

K. Webb ENGR 112


Flow Charts
6

 Flowcharts are graphical representations of


algorithms
 Interconnection of different types of blocks
 Start/End
 Process
 Conditional
 Input/Output

 Connection paths indicate flow from one step in the


procedure to the next
 Well-constructed flowcharts are easily translated
into code later
K. Webb ENGR 112
Flowchart Blocks
7

 Start/End
 Always indicate the start and end of any
flowchart
 Process
 Indicates the performance of some
action
 Conditional
 Performs a check and makes a decision
 Binary result: True/False, Yes/No, 1/0
 Algorithm flow branches depending on
result
 Input/Output
 Input or output of variables or data
K. Webb ENGR 112
Flowchart – Example
8

 Consider the very simple


example of making toast
 Process flows from Start to the
End through the process and
conditional blocks
 Arrows indicate flow
 Conditional blocks control flow
branching
 Note the loop defining the
waiting process
 Wait block is unnecessary

K. Webb ENGR 112


Flowchart – Example
9

 Flowchart for a given procedure


is not unique
 Varying levels of complexity and
detail are always possible
 Often important to think about
and account for various possible
outcomes and cases
 Forexample, is your toast always
done after it first pops up?
 Here, part of the procedure is
repeated if necessary
K. Webb ENGR 112
Flowchart – Example
10

 Taking this example further,


consider the possibility of burnt
toast or the desire for butter
 Another loop added for
continued scraping until edible
 Also possible to bypass portions
of the procedure – e.g., the
scraping of the toast or the
application of butter
 Can imagine significantly more
complex flow chart for the
same simple procedure …
K. Webb ENGR 112
11 Common Flowchart Structures

K. Webb ENGR 112


Common Flowchart Structures
12

 Several basic structures occur frequently in many


different types of flowcharts
 Recurrent basic structures in many algorithms
 Ultimately translate to recurrent code structures
 Two primary categories
 Conditional statements
 Loops

 In this section of notes, we’ll gain an understanding of


flowchart structures that fall into these two categories
 In the next section of notes we’ll learn how to
implement these structures in code
K. Webb ENGR 112
13 Conditional Statements
• if statements
• Logical and relational operators
• if…else statements

K. Webb ENGR 112


Conditional Statements – if
14

 Flowcharts represent a set of


instructions
 Blocks and block structures can be
thought of as statements
 Simplest conditional statement
is a single conditional block
 An if structure
 If X is true, then do Y, if not, don’t do Y
 In either case, then proceed to do Z
 Y and Z could be any type of process or action
 E.g. add two numbers, turn on a motor, butter the toast, etc.
 X is a logical expression or Boolean expression
 Evaluates to either true (1) or false (0)
K. Webb ENGR 112
Conditional Statements – if … else
15

 Can instead specify an action


to perform if X is not true
 An if … else structure
 If X is true, then do A, else do B

 Then, move on to do C

 Here, a different process is


performed depending on the
value of X (1/0, T/F, Y/N)

K. Webb ENGR 112


Conditional Statements – if … else
16

 Logical expression with a single


relational operator
𝑥𝑥 > 9
 Either true (Y) or false (N)
 If true, 𝑥𝑥 = 1
 If false, 𝑥𝑥 = −1

 Logical expression may also include a


logical operator
𝑥𝑥 > 9 || 𝑥𝑥 < −9
 Again, statement is either true or false
 Next process step dependent on value
of the conditional logical expression

K. Webb ENGR 112


Logical or Relational Expressions
17

 Logical expressions use logical and relational operators


Operator Relationship or Logical Operation Example

== Equal to x == b
~= Not equal to k ~= 0
< Less than t < 12
> Greater than a > -5
<= Less than or equal to 7 <= f
>= Greater than or equal to (4+r/6) >= 2
NOT– negates the logical value of an
~ expression
~(b < 4*g)
AND – both expressions must evaluate to
&& true for result to be true
(t > 0)&&(c == 5)
OR – either expression must evaluate to true
|| for result to be true
(p > 1)||(m > 3)

K. Webb ENGR 112


Logical Expressions – Examples
18

 Let 𝑥𝑥 = 12 and 𝑦𝑦 = −3
 Consider the following logical expressions:
Logical Expression Value

𝑥𝑥 + 𝑦𝑦 == 15 0

𝑦𝑦 == 2 || 𝑥𝑥 > 8 1

~ 𝑦𝑦 < 0 0

(𝑦𝑦/2 + 1 < −1) 0

𝑥𝑥 == 12 &&~(𝑦𝑦 ≥ 5) 1

𝑦𝑦~ = 2 || 𝑥𝑥 < 10 || 𝑥𝑥 < 𝑦𝑦 1

𝑥𝑥 == 2 && 𝑦𝑦 < 0 || 𝑥𝑥 ≥ 5 && 𝑦𝑦~ = 8 1

K. Webb ENGR 112


Conditional Statements – if … elseif … else
19

 Two conditional logical


expressions
 If the X is true, do A
 If X is false, evaluate Y
 If Y is true, do B
 If Y is false, do C

 The if … elseif … else


structure
 Can include an arbitrary
number of elseif statements
 Successive logical statements evaluated only if preceding
statement is false

K. Webb ENGR 112


if … elseif … else – Example
20

 Consider a
piecewise linear
function of 𝑥𝑥
 𝑦𝑦 = 𝑓𝑓(𝑥𝑥) not
defined by a single
function
 Function depends
on the value of 𝑥𝑥
 Can implement
with an
if … elseif … else
structure

K. Webb ENGR 112


if Statements – Other Configurations
21

 In previous examples, successive logical statements only


evaluated if preceding statement is false
 Result of a true logical expression can also be the
evaluation of a second logical expression

K. Webb ENGR 112


22 Loops
• while loops
• for loops

K. Webb ENGR 112


Loops
23

 We’ve already seen some examples of flow charts


that contain loops:

 Structures where the algorithmic flow loops back and


repeats process steps
 Repeats as long as a certain condition is met, e.g., toaster
has not popped up, toast is inedible, etc.
K. Webb ENGR 112
Loops
24

 Algorithms employ two primary types of loops:


 while loops: loops that execute as long as a specified
condition is met – loop executes as many times as is
necessary
 for loops: loops that execute a specified exact number
of times
 Similar looking flowchart structures
 forloop can be thought of as a special case of a while
loop
 However, the distinction between the two is very
important
K. Webb ENGR 112
25 while Loop

K. Webb ENGR 112


while Loop
26

 Repeatedly execute an instruction or set of instructions


as long as (while) a certain condition is met (is true)
 Repeat A while X is true
 As soon as X is no longer true, break
out of the loop and continue on to B
 A may never execute

 A may execute only once

 A may execute forever – an infinite


loop
 If A never causes X to be false
 Usually not intentional

K. Webb ENGR 112


while Loop
27

 Algorithm loops while 𝑥𝑥 ≤ 4


 Loops three times:
Iteration x
0 1
1 6
3
2 8
4
3 9
4.5

 Value of 𝑥𝑥 exceeds 4 several times during


execution
 𝑥𝑥 value checked at the beginning of the loop
 Final value of 𝑥𝑥 is greater than 4
K. Webb ENGR 112
while Loop – Infinite Loop
28

 Now looping continues as long as 𝑥𝑥 < 12


 𝑥𝑥 never exceeds 12
 Loops forever – an infinite loop
Iteration x
0 1
1 6
3
2 8
4
3 9
4.5
4 9.5
4.75
5 9.75
4.875
6 9.875
4.9375
⋮ ⋮
K. Webb ENGR 112
Infinite Loops
29

 Occasionally infinite loops are


desirable
 Consider for example microcontroller
code for an environmental monitoring
system
 Continuously takes measurements and
displays results while powered on
 Note the logical statement in the
conditional block
 Logical statements are either true (Y, 1)
or false (N, 0)
 1 is the Boolean representation of true
or Y
K. Webb ENGR 112
while Loop – Example 1
30

 Consider the following


algorithm:
 Read in a number (e.g. user
input, from a file, etc.)
 Determine the number of times
that number can be
successively divided by 2 before
the result is ≤ 1

 Use a while loop


 Divide by 2 while number is > 1

K. Webb ENGR 112


while Loop – Example 1
31

 Number of loop iterations


depends on value of the input
variable, x
 Characteristic of while loops
# of iterations unknown a priori
 If x ≤ 1 loop instructions never
execute

 Note the data I/O blocks


 Typical – many algorithms
have inputs and outputs

K. Webb ENGR 112


while Loop – Example 1
32

 Consider a few different input,


x, values:

count x x x
0 5 16 0.8
1 2.5 8 -
2 1.25 4 -
3 0.625 2 -
4 - 1 -
5 - - -

K. Webb ENGR 112


while Loop – Example 2
33

 Next, consider an algorithm to


calculate x!, the factorial of x:
 Read in a number, x
 Compute the product of all
integers between 1 and x
 Initialize result, fact, to 1
 Multiply fact by x
 Decrement x by 1

 Use a while loop


 Multiply fact by x, then
decrement x while x > 1
K. Webb ENGR 112
while Loop – Example 2
34

 Consider a few different input,


x, values:

x fact x fact x fact


5 1 4 1 0 1
5 5 4 4 - -
4 20 3 12 - -
3 60 2 24 - -
2 120 1 24 - -
1 120 - - - -

K. Webb ENGR 112


while Loop – Example 2
35

 Let’s say we want to define our


factorial algorithm only for
integer arguments
 Add error checking to the
algorithm
 After reading in a value for x,
check if it is an integer
 If not, generate an error message
and exit
 Could also imagine rounding x,
generating a warning message
and continuing

K. Webb ENGR 112


36 for Loop

K. Webb ENGR 112


for Loop
37

 We’ve seen that the number of while loop iterations is


not known ahead of time
 May depend on inputs, for example
 Sometimes we want a loop to execute an exact,
specified number of times
 A for loop
 Utilize a loop counter
 Increment (or decrement) the counter on each iteration
 Loop until the counter reaches a certain value

 Can be thought of as a while loop with the addition of a


loop counter
 But, a very distinct entity when implemented in code

K. Webb ENGR 112


for Loop
38

 Initialize the loop counter


 i, j, k are common, but name
does not matter
 Set the range for i
 Not necessary to define
variable istop
 Execute loop instructions, A
 Increment loop counter, i
 Repeat until loop counter
reaches its stopping value
 Continue on to B
K. Webb ENGR 112
for Loop
39

 for loops are counted loops


 Number of loop iterations is
known and is constant
 Here loop executes 10 times
 Stopping value not
necessarily hard-coded
 Could depend on an input or
vector size, etc.

K. Webb ENGR 112


for Loop
40

 Loop counter may start at


value other than 1
 Increment size may be a
value other than 1
 Loop counter may count
backwards
Iteration cntr Process
1 6 A
2 4 A
3 2 A
4 0 A
5 -2 A
6 -4 B

K. Webb ENGR 112


for Loop – Example 1
41

 Here, the loop counter, i, is used


to update a variable, x, on each
iteration
Iteration i x
1 1 1
2 2 4
3 3 9
4 4 16
5 5 25
 When loop terminates, and flow
proceeds to the next process
step, x = 25
 A scalar
 No record of previous values of x
K. Webb ENGR 112
for Loop – Example 2
42

 Now, modify the loop process to store


values of x as a vector
 Use loop counter to index the vector

i x(i) x
1 1 [1]
2 4 [1, 4]
3 9 [1, 4, 9]
4 16 [1, 4, 9, 16]
5 25 [1, 4, 9, 16, 25]

 When loop terminates,


x = [1, 4, 9, 16, 25]
 A vector
 x grows with each iteration
K. Webb ENGR 112
for Loop – Example 3
43

 The loop counter does not


need to be used within the
loop
 Used as a counter only
 Here, a random number is
generated and displayed
each of the 10 times through
the loop
 Counter, i, has nothing to do
with the values of the
random numbers displayed
K. Webb ENGR 112
for Loop – Example 4
44

 Have a vector of values, x


 Find the mean of those
values
 Sum all values in x
 A for loop
# of iterations equal to the
length of x
 Loop counter indexes x

 Divide the sum by the


number of elements in x
 After exiting the loop
K. Webb ENGR 112
45 Nested Loops

K. Webb ENGR 112


Nested Loops
46

 A loop repeats some process some number of times


 The repeated process can, itself, be a loop
 A nested loop

 Can have nested for loops or while loops


 Can nest for loops within while loops and vice versa
 One application of a nested for loop is to step
through every element in a matrix
 Loop counter variables used as matrix indices
 Outer loop steps through rows (or columns)

 Inner loop steps through columns (or rows)

K. Webb ENGR 112


Nested for Loop – Example
47

 Recall how we index the elements within a matrix:


 𝐴𝐴𝑖𝑖𝑖𝑖 is the element on the 𝑖𝑖 𝑡𝑡𝑡 row and 𝑗𝑗𝑡𝑡𝑡 column of the matrix 𝐴𝐴
 Using MATLAB syntax: A(i,j)
 Consider a 3 × 2 matrix
−2 1
𝐵𝐵 = 0 8
7 −3
 To access every element in 𝐵𝐵:
 start on the first row and increment through all columns
 Increment to the second row and increment through all columns
 Continue through all rows
 Two nested for loops

K. Webb ENGR 112


Nested for Loop – Example
48

−2 1
𝐵𝐵 = 0 8
7 −3
 Generate a matrix 𝐶𝐶
whose entries are the
squares of all of the
elements in 𝐵𝐵
 Nested for loop
 Outer loop steps through
rows
 Counter is row index
 Inner loop steps through
columns
 Counter is column index
K. Webb ENGR 112
49 Pseudocode & Top-Down Design

K. Webb ENGR 112


Pseudocode
50

 Flowcharts provide a useful tool for designing


algorithms
 Allow for describing algorithmic structure
 Ultimately used for generation of code

 Details neglected in favor of concise structural and


functional description
 Pseudocode provides a similar tool
 One step closer to actual code
 Textual description of an algorithm

 Natural language mixed with language-specific syntax

K. Webb ENGR 112


Pseudocode – Example
51

 Consider an algorithm for


determining the maximum of a
vector of values
 Pseudocode might look like:
N = length of x
max_x = x(1)
for i = 2:N
if x(i) is greater than current
max_x, then set max_x = x(i)
end

 Note the for loop syntax


 We’ll cover this in the following
section of notes

K. Webb ENGR 112


Top-Down Design
52

 Flowcharts and pseudocode are useful tools for top-


down design
 A good approach to any complex engineering design (and
writing, as well)
 First, define the overall system or algorithm at the top level
(perhaps as a flowchart)
 Then, fill in the details of individual functional blocks

 Top-level flowchart identifies individual functional


blocks and shows how each fits into the algorithm
 Each functional block may comprise its own flow chart or
even multiple levels of flow charts
 Hierarchical design

K. Webb ENGR 112


Top-Down Design - Example
53

 Let’s say you have deflection data from FEM


analysis of a truss design
 Data stored in text files
 Deflection vs. location along truss
 Parametric study
 Three different component thicknesses
 Two different materials
 Six data sets

 Read in the data, calculate the max deflection and


plot the deflection vs. position

K. Webb ENGR 112


Top-Down Design - Example
54

Level 1: Level 2: Level 3:

K. Webb ENGR 112

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy