If you're seeing this message, it means we're having trouble loading external resources on our website.
If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.
To log in and use all the features of Khan Academy, please enable JavaScript in your browser.
APÂŽď¸/College Computer Science Principles
Course: apÂŽď¸/college computer science principles  >  unit 4, the building blocks of algorithms.
- Expressing an algorithm
Want to join the conversation?
- Upvote Button navigates to signup page
- Downvote Button navigates to signup page
- Flag Button navigates to signup page
- AC Circuits
- Attenuators
- Binary Numbers
- Boolean Algebra
- Combinational Logic
- DC Circuits
- Electromagnetism
- Input/Output Devices
- Logic Gates
- Miscellaneous Circuits
- Operational Amplifiers
- Power Electronics
- Power Supplies
- RC Networks
- Sequential Logic
- Transformers
- Transistors
- Waveform Generators
- Premium content
- Further Education
- Connectivity
- Premium Content
Advertisement
Sequential Logic Circuits
Sequential Logic Circuits use flip-flops as memory elements and in which their output is dependent on the input state
Unlike Combinational Logic circuits that change state depending upon the actual signals being applied to their inputs at that time, Sequential Logic circuits have some form of inherent “Memory” built in.
This means that sequential logic circuits are able to take into account their previous input state as well as those actually present, a sort of “before” and “after” effect is involved with sequential circuits.
In other words, the output state of a “sequential logic circuit” is a function of the following three states, the “present input”, the “past input” and/or the “past output”. Sequential Logic circuits remember these conditions and stay fixed in their current state until the next clock signal changes one of the states, giving sequential logic circuits “Memory”.
Sequential logic circuits are generally termed as two state or Bistable devices which can have their output or outputs set in one of two basic states, a logic level “1” or a logic level “0” and will remain “latched” (hence the name latch) indefinitely in this current state or condition until some other input trigger pulse or signal is applied which will cause the bistable to change its state once again.
Sequential Logic Representation
The word “Sequential” means that things happen in a “sequence”, one after another and in Sequential Logic circuits, the actual clock signal determines when things will happen next. Simple sequential logic circuits can be constructed from standard Bistable circuits such as: Flip-flops , Latches and Counters and which themselves can be made by simply connecting together universal NAND Gates and/or NOR Gates in a particular combinational way to produce the required sequential circuit.
Classification of Sequential Logic
As standard logic gates are the building blocks of combinational circuits, bistable latches and flip-flops are the basic building blocks of sequential logic circuits. Sequential logic circuits can be constructed to produce either simple edge-triggered flip-flops or more complex sequential circuits such as storage registers, shift registers, memory devices or counters. Either way sequential logic circuits can be divided into the following three main categories:
- 1. Event Driven â asynchronous circuits that change state immediately when enabled.
- 2. Clock Driven â synchronous circuits that are synchronised to a specific clock signal.
- 3. Pulse Driven â which is a combination of the two that responds to triggering pulses.
As well as the two logic states mentioned above logic level “1” and logic level “0”, a third element is introduced that separates sequential logic circuits from their combinational logic counterparts, namely TIME . Sequential logic circuits return back to their original steady state once reset and sequential circuits with loops or feedback paths are said to be “cyclic” in nature.
We now know that in sequential circuits changes occur only on the application of a clock signal making it synchronous, otherwise the circuit is asynchronous and depends upon an external input. To retain their current state, sequential circuits rely on feedback and this occurs when a fraction of the output is fed back to the input and this is demonstrated as:
Sequential Feedback Loop
The two inverters or NOT gates are connected in series with the output at Q fed back to the input. Unfortunately, this configuration never changes state because the output will always be the same, either a “1” or a “0”, it is permanently set. However, we can see how feedback works by examining the most basic sequential logic components, called the SR flip-flop .
Sequential Logic SR Flip-Flops
The SR flip-flop , also known as a SR Latch , can be considered as one of the most basic sequential logic circuit possible. This simple flip-flop is basically a one-bit memory bistable device that has two inputs, one which will “SET” the device (meaning the output = “1”), and is labelled S and one which will “RESET” the device (meaning the output = “0”), labelled R .
Then the SR description stands for “Set-Reset”. The reset input resets the flip-flop back to its original state with an output Q that will be either at a logic level “1” or logic “0” depending upon this set/reset condition.
A basic NAND gate SR flip-flop circuit provides feedback from both of its outputs back to its opposing inputs and is commonly used in memory circuits to store a single data bit. Then the SR flip-flop actually has three inputs, Set , Reset and its current output Q relating to it’s current state or history.
The term “ Flip-flop ” relates to the actual operation of the device, as it can be “flipped” into one logic Set state or “flopped” back into the opposing logic Reset state.
Sequential Logic – The NAND Gate SR Flip-Flop
The simplest way to make any basic single bit set-reset SR flip-flop is to connect together a pair of cross-coupled 2-input NAND gates as shown, to form a Set-Reset Bistable also known as an active LOW SR NAND Gate Latch , so that there is feedback from each output to one of the other NAND gate inputs.
This device consists of two inputs, one called the Set , S and the other called the Reset , R with two corresponding outputs Q and its inverse or complement Q (not-Q) as shown below.
The Basic SR Flip-flop
The set state.
Consider the circuit shown above. If the input R is at logic level “0” (R = 0) and input S is at logic level “1” (S = 1), the NAND gate Y has at least one of its inputs at logic “0” therefore, its output Q must be at a logic level “1” (NAND Gate principles). Output Q is also fed back to input “A” and so both inputs to NAND gate X are at logic level “1”, and therefore its output Q must be at logic level “0”.
Again NAND gate principals. If the reset input R changes state, and goes HIGH to logic “1” with S remaining HIGH also at logic level “1”, NAND gate Y inputs are now R = “1” and B = “0”. Since one of its inputs is still at logic level “0” the output at Q still remains HIGH at logic level “1” and there is no change of state. Therefore, the flip-flop circuit is said to be “Latched” or “Set” with Q = “1” and Q = “0”.
Reset State
In this second stable state, Q is at logic level “0”, ( not Q = “0”) its inverse output at Q is at logic level “1”, ( Q = “1”), and is given by R = “1” and S = “0”.
As gate X has one of its inputs at logic “0” its output Q must equal logic level “1” (again NAND gate principles). Output Q is fed back to input “B”, so both inputs to NAND gate Y are at logic “1”, therefore, Q = “0”.
If the set input, S now changes state to logic “1” with input R remaining at logic “1”, output Q still remains LOW at logic level “0” and there is no change of state. Therefore, the flip-flop circuits “Reset” state has also been latched and we can define this “set/reset” action in the following truth table.
Truth Table for this Set-Reset Function
It can be seen that when both inputs S = “1” and R = “1” the outputs Q and Q can be at either logic level “1” or “0”, depending upon the state of the inputs S or R BEFORE this input condition existed. Therefore the condition of S = R = “1” does not change the state of the outputs Q and Q .
However, the input state of S = “0” and R = “0” is an undesirable or invalid condition and must be avoided. The condition of S = R = “0” causes both outputs Q and Q to be HIGH together at logic level “1” when we would normally want Q to be the inverse of Q .
The result is that the flip-flop looses control of Q and Q , and if the two inputs are now switched “HIGH” again after this condition to logic “1”, the flip-flop becomes unstable and switches to an unknown data state based upon the unbalance as shown in the following switching diagram.
S-R Flip-flop Switching Diagram
This unbalance can cause one of the outputs to switch faster than the other resulting in the flip-flop switching to one state or the other which may not be the required state and data corruption will exist. This unstable condition is generally known as its Meta-stable state.
Then, a simple NAND gate SR flip-flop or NAND gate SR latch can be set by applying a logic “0”, (LOW) condition to its Set input and reset again by then applying a logic “0” to its Reset input. The SR flip-flop is said to be in an “invalid” condition (Meta-stable) if both the set and reset inputs are activated simultaneously.
As we have seen above, the basic NAND gate SR flip-flop requires logic “0” inputs to flip or change state from Q to Q and vice versa. We can however, change this basic flip-flop circuit to one that changes state by the application of positive going input signals with the addition of two extra NAND gates connected as inverters to the S and R inputs as shown.
Positive NAND Gate SR Flip-flop
As well as using NAND gates, it is also possible to construct simple one-bit SR Flip-flops using two cross-coupled NOR gates connected in the same configuration. The circuit will work in a similar way to the NAND gate circuit above, except that the inputs are active HIGH and the invalid condition exists when both its inputs are at logic level “1”, and this is shown below.
The NOR Gate SR Flip-flop
Sequential logic as switch debounce circuits.
Edge-triggered flip-flops require a nice clean signal transition, and one practical use of this type of set-reset circuit is as a latch used to help eliminate mechanical switch “bounce”. As its name implies, switch bounce occurs when the contacts of any mechanically operated switch, push-button or keypad are operated and the internal switch contacts do not fully close cleanly, but bounce together first before closing (or opening) when the switch is pressed.
This gives rise to a series of individual pulses which can be as long as tens of milliseconds that an electronic system or circuit such as a digital counter may see as a series of logic pulses instead of one long single pulse and behave incorrectly.
For example, during this bounce period the output voltage can fluctuate wildly and may register multiple input counts instead of one single count. Then set-reset SR Flip-flops or Bistable Latch circuits can be used to eliminate this kind of problem and this is demonstrated below.
SR Flip Flop Switch Debounce Circuit
Depending upon the current state of the output, if the set or reset buttons are depressed the output will change over in the manner described above and any additional unwanted inputs (bounces) from the mechanical action of the switch will have no effect on the output at Q .
When the other button is pressed, the very first contact will cause the latch to change state, but any additional mechanical switch bounces will also have no effect. The SR flip-flop can then be RESET automatically after a short period of time, for example 0.5 seconds, so as to register any additional and intentional repeat inputs from the same switch contacts, such as multiple inputs from a keyboards “RETURN” key.
Commonly available IC’s specifically made to overcome the problem of switch bounce are the MAX6816, single input, MAX6817, dual input and the MAX6818 octal input switch debouncer IC’s. These chips contain the necessary flip-flop circuitry to provide clean interfacing of mechanical switches to digital systems.
Set-Reset bistable latches can also be used as Monostable (one-shot) pulse generators to generate a single output pulse, either high or low, of some specified width or time period for timing or control purposes. The 74LS279 is a Quad SR Bistable Latch IC, which contains four individual NAND type bistable’s within a single chip enabling switch debounce or monostable/astable clock circuits to be easily constructed.
Quad SR Bistable Latch 74LS279
Sequential logic – gated or clocked sr flip-flops.
It is sometimes desirable in sequential logic circuits to have a bistable SR flip-flop that only changes state when certain conditions are met regardless of the condition of either the Set or the Reset inputs.
By connecting a 2-input AND gate in series with each input terminal of the SR Flip-flop a Gated SR Flip-flop can be created. This extra conditional input is called an “Enable” input and is given the prefix of “ EN “. The addition of this input means that the output at Q only changes state when it is HIGH and can therefore be used as a clock (CLK) input making it level-sensitive as shown below.
Gated SR Flip-flop
When the Enable input “EN” is at logic level “0”, the outputs of the two AND gates are also at logic level “0”, (AND Gate principles) regardless of the condition of the two inputs S and R , latching the two outputs Q and Q into their last known state.
When the enable input “EN” changes to logic level “1” the circuit responds as a normal SR bistable flip-flop with the two AND gates becoming transparent to the Set and Reset signals.
This additional enable input can also be connected to a clock timing signal (CLK) adding clock synchronisation to the flip-flop creating what is sometimes called a “ Clocked SR Flip-flop “.
So a Gated Bistable SR Flip-flop operates as a standard bistable latch but the outputs are only activated when a logic “1” is applied to its EN input and deactivated by a logic “0”.
In the next tutorial about Sequential Logic Circuits , we will look at another type of simple edge-triggered flip-flop which is very similar to the RS flip-flop called a JK Flip-flop named after its inventor, Jack Kilby. The JK flip-flop is the most widely used of all the flip-flop designs as it is considered to be a universal device.
Read more Tutorials inSequential Logic
- 1. Sequential Logic Circuits
- 2. The JK Flip Flop
- 3. Multivibrators
- 4. The D-type Flip Flop
- 5. The Shift Register
- 6. Johnson Ring Counter
- 7. Conversion of Flip-flops
- 8. The Toggle Flip-flop
195 Comments
Notify me of follow-up comments by email.
The author apparently has no idea of the difference between a latch and a flip-flop. There is no such thing as an SR flip flop.
Oh, really. Let’s start with some basic facts about the difference between a Latch and a Flip-flop.
An asynchronous flip-flop is a bistable storage element which has two inputs. A Set (S) and a Reset (R), plus two outputs, Q and not-Q. The set-reset (SR) flip-flop has two stable states and the ability to indefinitely hold a specific state (0 or 1) until it is toggled between either of these two states. Synchronous SR flip-flops load a new state when triggered by the transition of an input clock signal. The main types of flip-flop being: SR (sometimes termed RS), and JK.
A relative of the flip-flop is the data latch, which is also capable of retaining its state indefinitely due to its ability to latch and remember data. A latch does not have a clock signal to change state but has a data input (D), a Q output, and an enable (EN) input. When enabled, the input data is passed directly to the output. That is, a data latch operates more like an AND gate than a bistable storage Set-Reset device. Also latches are level sensitive, whereas flip-flops are edge sensitive. The main types of latch are: D-type, and T-type.
Then, it appears you are the one confused about the difference between latches and flip-flops and the existance of Set-Reset flip-flops as one of the simplest 1-bit memory storage cicruits.
what is this man
I like the site
very informative .
Electronic s is great
So very basic from
Explain The State of A sequential Circuit A state variable in a sequential circuit represents the single-bit variable Q stored in a memory element in circuit. â Each memory element may be in state 0 or state 1 depending on the current value stored in the memory element. The State of A sequential Circuit: â The collection of all state variables (memory element stored values) that at any time contain all the information about the past necessary to account for the circuitâs future behavior. â A sequential circuit that contains n memory elements could be in one of a maximum of 2n states at any given time depending on the stored values in the memory elements. â Sequential Circuit State transition: A change in the stored values in memory elements thus changing the sequential circuit from one state to another.
This is so powerful. Which sequencing is used in engine control unit C.P.U.
Which logic gate do you add to convert an S-R latch to an S-R latch with Enable?
Please read the Gated SR flip-flop part of the tutorial
Why are the outputs stated to be inverse? I see no reason that the inputs 0 and 0 could not generate outputs of 1 and 1 apart from the assertion that the outputs are inverse. Noone seems to explain why these outputs cannot be identical.
Because then it would not be a Bistable Latch, just another logic circuit. You could add an inverter (NOT Gate) onto one of the outputs to achieve 0-0 or 1-1. But what’s the point.
Different between JK flip flop and SR flip flop
Please read the tutorials about JK and SR flip-flops
In the circuit of Figure 1, inputs A, B, and C are all initially LOW. Output Y is supposed to go HIGH only when A, B, and C go HIGH in a certain sequence. Analyze the circuit to
(a) Determine the sequence that will make Y go HIGH. (b) Explain why the START pulse is needed. (c) Modify this circuit to use D FFs.
Understandable
How can I make a shift register that shifts left but each output stays on after shift until all outputs are on? Need 16 points. I think I need a latch for each output, 4 shift register chips also can the sft drive LEDs direct or I need a transistor?
First truth table you got has QⲠthat merges with the background color.
This video provided a great support hence it is much appreciated in relation to the studies carried out so far,I therefore encourage you to keep on maintaining such a good character in researching and providing such a power of study. The research carried so far seems to hold more water that whenever i want to attend a lecture it will be far much better for me to understand who is the best of all between the google scholar and other social media platforms such as whatsApp and facebook. Adding more on that i aslo encouraged you to keep on doing the great work seen from the University of Zimbabwe under the leaderslhip of Changamire dombo here under the construction of the Great Universityunder the leadership of Engineer DR Charless
I loved this
How many type of truth table in s-r flip-flop ?
- Privacy Policy
- Terms of Use
- Contact Sales
- Media Guide Request
- Electronic Products
- Power Electronics News
- Planet Analog
- ElectroSchematics
- Datasheets.com
- Electronics Know How
- The Channelist
- EE Times Asia
- EE Times China
- EE Times India
- EE Times Japan
- EE Times Taiwan
Privacy Overview
- Get started with computers
- Learn Microsoft Office
- Apply for a job
- Improve my work skills
- Design nice-looking docs
- Getting Started
- Smartphones & Tablets
- Typing Tutorial
- Online Learning
- Basic Internet Skills
- Online Safety
- Social Media
- Zoom Basics
- Google Docs
- Google Sheets
- Career Planning
- Resume Writing
- Cover Letters
- Job Search and Networking
- Business Communication
- Entrepreneurship 101
- Careers without College
- Job Hunt for Today
- 3D Printing
- Freelancing 101
- Personal Finance
- Sharing Economy
- Decision-Making
- Graphic Design
- Photography
- Image Editing
- Learning WordPress
- Language Learning
- Critical Thinking
- For Educators
- Translations
- Staff Picks
- English expand_more expand_less
Computer Science - Sequences, Selections, and Loops
Computer science -, sequences, selections, and loops, computer science sequences, selections, and loops.
Computer Science: Sequences, Selections, and Loops
Lesson 5: sequences, selections, and loops.
/en/computer-science/programming-languages/content/
Sequences, selections, and loops
Behind all of the software we use on a daily basis, there's a code being run with all sorts of terms and symbols. Surprisingly, it can often be broken down into three simple programming structures called sequences , selections , and loops . These come together to form the most basic instructions and algorithms for all types of software.
Watch the video below to learn more about sequences, selections, and loops.
A sequence is a series of actions that is completed in a specific order . Action 1 is performed, then Action 2, then Action 3, etc., until all of the actions in the sequence have been carried out.
A sequence we do every day is a morning routine . You might wake up, drink some water, take a shower, eat breakfast, and so on. Everyone's routine is different, but they're all made up of a sequence of various actions .
Selections are a bit different. Instead of following a specific order of events, they ask a question in order to figure out which path to take next .
Let's say you go to brush your teeth, and you find that you're out of toothpaste. You'd then ask, "Do I have any more toothpaste?" If the answer is no , then you would add it to your shopping list . But if the answer is yes , you would just use the toothpaste . This is really all a selection is doing: answering a question based on what it finds .
The third programming structure is a loop . Like selections, loops ask questions. However, the difference is that they ask the same question over and over and over again, until a certain task is complete .
For example, take the act of hammering a nail. Even though you may not realize it, you're constantly asking yourself, "Is the nail all the way in?" When the answer is no , you hammer the nail again . You continue to repeat this question until the answer is yes , and then you stop . Loops allow programmers to efficiently code repetitive tasks instead of having to write the same actions over and over again.
These three programming structures may seem pretty simple on their own, but when combined they can create some pretty complex software.
/en/computer-science/should-i-learn-to-code/content/
Browse Course Material
Course info.
- Chris Terman
Departments
- Electrical Engineering and Computer Science
As Taught In
- Computer Design and Engineering
- Digital Systems
Learning Resource Types
Computation structures, 5 sequential logic.
BackWorksheet
ContinueAnnotated Slides
5.1 Annotated Slides
- 5.1.1 Annotated slides
5.2 Topic Videos
- 5.2.1 Digital State
- 5.2.2 D Latch
- 5.2.3 D Register
- 5.2.4 D Register Timing
- 5.2.5 Sequential Circuit Timing
- 5.2.6 Timing Example
- 5.2.7 Worked Example 1
- 5.2.8 Worked Example 2
5.3 Worksheet
5.3.1 Sequential Logic Worksheet
- Trending Now
- Data Structures & Algorithms
- Foundational Courses
- Data Science
- Practice Problem
- Machine Learning
- System Design
- DevOps Tutorial
- Web Development
- Web Browser
- Solve Coding Problems
- BCA 1st Semester Syllabus (2023)
Fundamentals of IT & Computers
- Basics of Computer and its Operations
- Characteristics of Computer System
- Types of Computers
- Number System and Base Conversions
- What is Algorithm | Introduction to Algorithms
- What is a Flowchart and its Types?
- What is an Operating System?
- DOS Full Form
- Types of Operating Systems
- Commonly Used Operating System
- Difference between Word Processor and Text Editor
- Introduction to Microsoft Word
- Introduction to MS Excel
- Introduction to Microsoft PowerPoint
C Programming
- C Programming Language Tutorial
- Operators in C
Control Structures in Programming Languages
- C if else if ladder
- Nested switch case
- Introduction to Divide and Conquer Algorithm - Data Structure and Algorithm Tutorials
- Understanding Time Complexity with Simple Examples
- What is PseudoCode: A Complete Tutorial
- Arithmetic Operators in C
- C Functions
- Parameter Passing Techniques in C
- Difference Between Call by Value and Call by Reference in C
- Scope rules in C
Basic Mathematics
- Determinant of a Matrix
- Mathematics | Limits, Continuity and Differentiability
- Advanced Differentiation
- Chain Rule Derivative - Theorem, Proof, Examples
- Taylor Series
- Relative Minima and Maxima
- Beta Function
- Gamma Function
- Reduction Formula
- Vector Algebra
Business Communication
- What is Communication?
- Communication and its Types
- BCA 2nd Semester Syllabus (2023)
- BCA 3rd Semester Syllabus (2023)
- BCA 4th Semester Syllabus (2023)
- BCA 5th Semester Syllabus (2023)
- BCA 6th Semester Subjects and Syllabus (2023)
- BCA Full Form
- Bachelor of Computer Applications: Curriculum and Career Opportunity
- Sequence logic, or sequential flow
- Selection logic, or conditional flow
- Iteration logic, or repetitive flow
Sequential Control flow
- C/C++ if statement with Examples
- Java if statement with Examples
- C/C++ if-else statement with Examples
- Java if-else statement with Examples
- C/C++ if-else if statement with Examples
- Java if-else if statement with Examples
Double Alternative Control Flow
Repeat-For Flow
- C/C++ for loop with Examples
- Java for loop with Examples
Repeat While Flow
- C/C++ while loop with Examples
- Java while loop with Examples
Please Login to comment...
- Programming Language
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- school Campus Bookshelves
- menu_book Bookshelves
- perm_media Learning Objects
- login Login
- how_to_reg Request Instructor Account
- hub Instructor Commons
- Download Page (PDF)
- Download Full Book (PDF)
- Periodic Table
- Physics Constants
- Scientific Calculator
- Reference & Cite
- Tools expand_more
- Readability
selected template will load here
This action is not available.
1.1: Activity 1 - Introduction to Algorithms and Problem Solving
- Last updated
- Save as PDF
- Page ID 48194
Introduction
In this learning activity section, the learner will be introduced to algorithms and how to write algorithms to solve tasks faced by learners or everyday problems. Examples of the algorithm are also provided with a specific application to everyday problems that the learner is familiar with. The learners will particularly learn what is an algorithm, the process of developing a solution for a given task, and finally examples of application of the algorithms are given.
An algorithm is a finite sequence of steps for accomplishing some computational task. It must
- Have steps that are simple and definite enough to be done by a computer, and
- Terminate after finitely many steps.
An algorithm can be considered as a computational procedure that consists of a set of instructions, that takes some value or set of values, as input, and produces some value or set of values, as output, as illustrated in Figure 1.3.1 . It can also be described as a procedure that accepts data, manipulate them following the prescribed steps, so as to eventually fill the required unknown with the desired value(s). The concept of an algorithm is best illustrated by the example of a recipe, although many algorithms are much more complex; algorithms often have steps that repeat (iterate) or require decisions (such as logic or comparison) until the task is completed. Correctly performing an algorithm will not solve a problem if the algorithm is flawed or not appropriate to the problem. A recipe is a set of instructions that show how to prepare or make something, especially a culinary dish.
Different algorithms may complete the same task with a different set of instructions in more or less time, space, or effort than others. Algorithms are essential to the way computers process information, because a computer program is essentially an algorithm that tells the computer what specific steps to perform (in what specific order) in order to carry out a specified task.
Algorithmic problem solving comes in two phases. These include:
- derivation of an algorithm that solves the problem, and
- conversion of the algorithm into code.
It is worth noting that:
- an algorithm is a sequence of steps, not a program.
- same algorithm can be used in different programs, or the same algorithm can be expressed in different languages, because an algorithm is an entity that is abstracted from implementation details.
An algorithm can be expressed in the following ways:
- human language
- pseudo code
Example \(\PageIndex{1}\)
Problem: Given a list of positive numbers, return the largest number on the list.
Inputs: A list L of positive numbers. This list must contain at least one number.
Outputs: A number n, which will be the largest number of the list.
- Set max to 0.
- For each number x in the list L, compare it to max. If x is larger, set max to x.
- max is now set to the largest number in the list.
The learner was introduced to the concept of algorithms and the various ways he/she can develop a solution to a task. In particular, the learner was introduced to the definition/s of an algorithm, the three main ways of developing or expressing an algorithm which are the human language, Pseudo code and the flow chart. An example was also given to reinforce the concept of the algorithm.
- Outline the algorithmic steps that can be used to add two given numbers.
- By using an example, describe how the concept of algorithms can be well presented to a group of students being introduced to it.
UNIT 4: Control Structures: Making Decisions and Looping in computing. Data and Information Processing in Python.
Learning objectives.
- Read and write programs using the Python IF and IF/ELIF/ELSE statements to implement a simple decision structures.
- Write simple exception handling code to catch simple Python run-time errors.
- Read and write programs using the Python FOR and WHILE statements to implement a simple loop structures.
- Construct and implement algorithms that use decision and loop structures.
- Apply basic file processing concepts and techniques for reading and writing text files in Python.
Boolean Expressions
- Logical Operators
- Conditional Execution
Arithmetic expressions evaluate to numeric values; a Boolean expression may have only one of two possible values: false or true . While on the surface Boolean expressions may appear very limited compared to numeric expressions, they are essential for building more interesting and useful programs.
The simplest Boolean expressions in Python are True and False . In the Python interactive shell we see:
We see that bool is the name of the class representing Pythonâs Boolean expressions. The following code (booleanVars.py) is a simple program that shows how Boolean variables can be used.
# Assign some Boolean variables a = True b = False print('a =', a, ' b =', b) # Reassign a a = False print('a =', a, ' b =', b)
The results of running this program are shown below:
A Boolean variable is also a Boolean expression as we saw in Unit 2. An expression comparing numeric expressions for equality or inequality is also a Boolean expression. The simplest kinds of Boolean expressions use relational operators (or comparison operators) to compare two expressions. Table 6 lists the relational operators available in Python.
Table 6: Python Relationa/Comparisonl Operators
In the Python interactive shell we see some examples of Boolean expressions:
An expression like 10 < 20 is legal but of little use, since 10 < 20 is always true; the expression True is equivalent, simpler, and less likely to confuse human readers. Since variables can change their values during a programâs execution (and often do!), Boolean expressions are most useful when their truth values depend on the values of one or more variables.
The relational/comparison operators are binary operators and are all left associative. They all have a lower precedence than any of the arithmetic operators; therefore, Python evaluates the expression
x + 2 < y / 10
as if parentheses were placed as so:
(x + 2) < (y / 10)
Logical operators
There are three logical operators: and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a Boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y .
Strictly speaking, the operands of the logical operators should be Boolean expressions, but Python is not very strict. Any nonzero number is interpreted as True :
This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).
Conditional execution
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:
Figure 41: Simple IF Conditional Flowchart
The Boolean expression after if is called the condition. If it is true, the indented statement runs. If not, nothing happens. See the corresponding flowchart in figure 42.
if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements.
There is no limit on the number of statements that can appear in the body, but there has to be at least one.
A second form of the if statement is âalternative executionâ ( if-else ), in which there are two possibilities and the condition determines which one runs. The syntax looks like this:
if x % 2 == 0: print('x is even') else: print('x is odd')
Figure 42: Alternative Execution Conditional Flowchart
Modulus or remainder operator , â % â, returns the remainder of two numbers. So in this example, i f the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution. See the corresponding flowchart in figure 42.
The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block ), else we process another block of statements (called the else-block ). The else clause is optional. In our earlier examples we only had one statement in a block. Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional ( if-elif-else ). The following program, ifElse.py , show s us multiple statements in each block.
number = 23 guess = int(input('Enter an integer : '))
if guess == number: # New block starts here print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') # New block ends here elif guess < number: # Another block print('No, it is a little higher than that') # You can do whatever you want in a block ... else: print('No, it is a little lower than that') # you must have guessed > number to reach here
print('Done') # This last statement is always executed, # after the if statement is executed.
In this program, we take guesses from the user and check if it is the number that we have. We set the variable number to any integer we want, say 23. Then, we take the userâs guess using the input() function. We then convert this string to an integer using int and then store it in the variable guess .
Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message. Notice that we use indentation levels to tell Python which statements belong to which block. Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little higher than that.
After Python has finished executing the complete if statement along with the associated elif and else clauses, it moves on to the next statement in the block containing the if statement. In this case, it is the main block (where execution of the program starts), and the next statement is the print('Done') statement. After this, Python sees the end of the program and simply finishes up.
The following code is another example of a conditional statement with more than two branches:
if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal')
Figure 43: Two or More Branches Conditional Flowchart
elif is an abbreviation of âelse ifâ. Again, exactly one branch will run. There is no limit on the number of elif statements. See the corresponding flowchart in figure 43. If there is an else clause, it has to be at the end, but there doesnât have to be one. See the following example:
if choice == 'a': draw_a() elif choice == 'b': draw_b() elif choice == 'c': draw_c()
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs. It is good practice to include the else clause as the final branch in the if-elif-else statement.
Practic e â Write a program to accept a test score as input and print out the corresponding letter grade. First examine the flowchart (figure 44) of the problem we are solving. Then, using the Python editor, enter the following code (save as testGrade.py ):
Figure 44: if-elif-else Conditional Flowchart
#accept a test score as input and print out the corresponding letter grade testScore = float(input("Enter a test score from 0 to 100: ")) # conditional statement to determine and print the test letter grade if testScore >= 90: print("your grade is A") elif testScore >= 80: print("your grade is B") elif testScore >= 70: print("your grade is C") elif testScore >= 60: print("your grade is D") else: print("your grade is F")
Let us examine how this program works.
One conditional can also be nested within another called nested conditionals . Earlier in this section we saw the following example using a chained conditional ( if-elif-else ).
if x < y:
print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal')
We could have just as easily written this code using nested conditionals like this:
if x == y: print('x and y are equal') else: if x < y: print('x is less than y') else: print('x is greater than y')
The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:
if 0 < x: if x < 10: print('x is a positive single-digit number.')
The print statement runs only if we make it past both conditionals, so we can get the same effect with the and operator:
if 0 < x and x < 10: print('x is a positive single-digit number.')
For this kind of condition, Python provides even a more concise option:
Exception Handling
In our programming experience so far we have encountered several kinds of programming run-time exceptions, such as division by zero, attempting to read a variable that has not been defined, and attempting to convert a non-number to an integer. We have seen these and other run-time exceptions immediately terminate a running program.
Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred. The Python interpreter raises an exception when it detects a run-time error (such as division by zero).
Python provides a standard mechanism called exception handling that allows programmers to deal with these kinds of run-time exceptions and many more. Rather than always terminating the programâs execution (this is called a program âcrashâ), an executing program can detect the problem when it arises and possibly execute code to correct the issue it in some way.
Exceptions occur when exceptional situations occur in your program. Similarly, what if your program had some invalid statements? This is handled by Python which raises its hands and tells you there is an error.
Consider the simple print function call. What if we misspell print as Print ? Note the capitalization. In this case, Python raises a syntax error. The following output appears in the Python shell. Observe that a NameError is raised and also the location of the error detected is printed. This is what an error handler for this error does.
>>>Print("hello there!") Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> Print("hello there!") NameError: name 'Print' is not defined >>> print("hello there!") hello there! >>>
Let us try to read input from the user. In the Python shell we enter the first line below and hit the Enter key. When the computer prompts for input, instead press [ctrl-c] (this example is with Windows) and see what happens.
Python raises an error called KeyboardInterrupt which basically means it was interrupted when it expected to get user input.
Let us look at another example. Here we will read input from the user and then attempt to convert the string input into an integer.
Python raises an error called ValueError which is letting us know that the string ânoâ cannot be converted to an integer value. Programmers can avoid this scenario by checking that a stringâs value can be converted to a number value.
Another common exception occurs when we try to evaluate a comparison which does not make sense. Consider the following Python conditional statements executed in the Shell window:
Python raises an error called TypeError which is letting us know that the condition 12 < 'a' cannot be performed.
Handling Exceptions
Essentially, exceptions are events that modify programâs flow, either intentionally or due to errors. They are special events that can occur due to an error, e.g. trying to divide a number by zero. Exceptions, by definition, donât occur very often; hence, they are the âexception to the ruleâ.
Exceptions are everywhere in Python. Virtually every module in the standard Python library uses them, and Python itself will raise them in a lot of different circumstances. One use of exceptions is to catch an error and allow the program to continue working instead of crashing ungracefully.
This is the most common way to use exceptions. When programming with the Python command line interpreter (in the Shell window), you donât need to worry about catching exceptions. Your program is usually short enough to not be hurt too much if an exception occurs. Plus, having the exception occur at the command line is a quick and easy way to tell if your code logic has a problem. However, if the same error occurred in your saved .py file program, it will crash (fail) and stop working.
Exceptions can be thought of as a special form of the if-else statements. You can realistically do the same thing with if blocks as you can with exceptions. However, as already mentioned, exceptions arenât processed until they occur; if blocks are processed all the time. Proper use of exceptions can help the performance of your program. The more infrequent the error might occur, the better off you are to use exceptions; using if blocks requires Python to always test extra conditions before continuing. Exceptions also make code management easier: if your programming logic is mixed in with error-handling if statements, it can be difficult to read, modify, and debug your program.
We can handle exceptions using the try-except-else statement. Briefly, try creates a block that attempts to perform an action. If that action fails, the except block catches any exception that is raised and notifies the user that an error occurred, then stops executing the program. If the code within the try block does not produce an exception, the programâs execution continues with code in the else block.
Practice â Here is a simple program that uses exception processing. It simply produces the quotient of 2 numbers. Try entering, saving and running the following program ( exceptionHandling.py ).
# exception handling first_number = input ( "Enter the first number: ") #gets input from keyboard sec_number = input ( "Enter the second number: " ) try : num1 = float( first_number ) #try turning keyboard input into floats num2 = float( sec_number ) result = num1/num2 #try dividing num1 by num2 except: print("Error: enter numbers only; num2 cannot equal zero") else : print(str(num1) + "/" + str(num2) + "=" + str(result))
The output from executing this program, three separate times, is shown below.
In this example we simply print out a message to the user in the except block and then gracefully terminate our program. We use the else statement at the end to perform the rest of the program logic if all goes well. As stated before, the whole try block could also have been written as if/else statements but that would have required Python to process each statement to see if they matched. By using exceptions, the âdefaultâ case is assumed to be true until an exception actually occurs. This speeds up processing.
Itâs better to include error-checking, such as exceptions, in your code as you program rather than as an afterthought. A special âcategoryâ of programming involves writing test cases (we wrote test cases for our algorithms in Unit 1!) to ensure that most possible errors are accounted for in the code, especially as the code changes or new versions are created. Recall the test cases we were introduced to when writing our algorithms in Unit 1. By planning ahead and putting exception handling into your program at the outset, you ensure that problems are caught before they can cause problems.
Practice with Handling Exceptions in our Programs
Let us review some examples of handling exceptions in some of our programs we have written.
Practice #1 â Calculating the distance between two points:
# calculates the distance between two points
import math
print("This program calculates the distance between two points.") print() #print a blank line
x1 = float(input("Enter the x for the first point: ")) y1 = float(input("Enter the y for the first point: ")) print() x2 = float(input("Enter the x for the second point: ")) y2 = float(input("Enter the y for the second point: "))
distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print() print("The distance between the points is", distance)
The output when executing this program with non-numeric input is seen below:
Rewrite this program to include exception handling to catch the ValueError when we try and convert our user input into floating point numbers.
# Calculates the distance between two points
print("This program calculates the distance between two points.") print() try: x1 = float(input("Enter the x for the first point: ")) y1 = float(input("Enter the y for the first point: ")) print() x2 = float(input("Enter the x for the second point: ")) y2 = float(input("Enter the y for the second point: ")) except: print("Error: enter numeric values only") else: distance = math.sqrt((x2-x1)**2 + (y2-y1)**2) print() print("The distance between the points is", distance)
The output when executing the revised program with non-numeric input is far more user friendly!
>>> RESTART: C:/Users/lh166266.UALBANY/distanceBetweenPointsExceptionHandling.py This program calculates the distance between two points. Enter the x for the first point: 17 Enter the y for the first point: 23 Enter the x for the second point: 88 Enter the y for the second point:9p Error: enter numeric values only >>>
Practice # 2 â Guess the Number:
number = 23 guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') elif guess < number: print('No, it is a little higher than that') else: print('No, it is a little lower than that')
print('Done')
Rewrite this program to include exception handling to catch the ValueError when we try and convert the user input into an integer.
# Guess my number
number = 23 . #this is âmy numberâ try: guess = int(input('Enter an integer : ')) except: print("ERROR: enter whole numbers only") else: if guess == number: print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') elif guess < number: print('No, it is a little higher than that') else: print('No, it is a little lower than that')
The output when executing the revised program with non-numeric input gracefully ends rather than crashing!
This section is about iteration, which is the ability to run a block of statements repeatedly. Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration.
The while Statement
A while statement is an iterative control statement that repeatedly executes a set of statements based on a provided Boolean expression (condition). All iterative control needed in a program can be achieved by use of the while statement, though, as we will see later, other iterative control statements can be more useful for solving some computational problems.
Here is a version of a countdown function that uses a while statement:
def countdown(n): while n > 0: print(n) n = n - 1 print('Blastoff!')
Figure 45: While Loop Flowchart
You can almost read the while statement as if it were English. It means, âWhile n is greater than 0, display the value of n and then decrement n. When you get to 0, display the word Blastoff!â
Here is the flow of execution for a while statement:
- Determine whether the condition is true or false.
- If false, exit the while statement and continue execution at the next statement.
- If the condition is true, run the body and then go back to step 1.
This type of flow is called a loop because the third step loops back around to the top.
The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.
In the case of the countdown function, we can prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise, n gets smaller each time through the loop, so eventually we have to get to 0.
Practice 1 : Try executing the following program which uses the countdown function ( countdown.py ).
def countdown(n): while n > 0: print(n) n = n - 1 print('Blastoff!') num = input("enter a positive number to countdown from: ")
try: num=int(num) except: print("ERROR: enter a whole number") else: countdown(num)
An example of the output after execution:
The variable n in the countdown.py program is referred to as a counter . A counter variable is used to count something, usually initialized to zero and then incremented (or decremented) and is commonly used in programs.
The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause. Let us look at the following program ( while.py )
number = 23 running = True
while running: guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations, you guessed it.') # this causes the while loop to stop running = False elif guess < number: print('No, it is a little higher than that.') else: print('No, it is a little lower than that.') else: print('The while loop is over.') # Do anything else you want to do here
In this program, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly â there is no need to repeatedly run the program for each guess, as we have done in the previous section. This aptly demonstrates the use of the while statement. Let us examine more closely the code in this program ( while.py ) .
The following is a sample of output after running this program:
This is an example of an interactive loop because it allows the user to repeat something (in this example the user is guessing a number) on demand.
Practice 2 : The following program allows a user to enter any number of nonnegative integers. When the user enters a negative value, the program no longer accepts input, and it displays the sum of all the nonnegative values. If a negative number is the first entry, the sum is zero. This is also an example of interactive loop . [ addNonNegatives.py ]
Figure 46: Sample Output from addNonNegatives.py
Figure 47: While Loop Flowchart
Let us examine more closely the code in this program.
Practice 3 : Now let us rewrite this program to add additional functionality. In addition to finding the sum of nonnegative values we will calculate the average. [ avgNonNegatives.py ]
The program needs not only an accumulator variable (i.e. sum ) but a counter variable also (named count ) to keep track of how many numbers have been entered. We can then calculate the average by dividing the sum by the count.
RESTART: C:/Users/lh166266.UALBANY/Code/avgNonNegatives.py Enter positive numbers to sum (entering a negative number ends the program). number: 12 number: 55 number: 31 number: -11 Sum = 98 Average = 32.666666666666664
Figure 48: Sample Output from avgNonNegatives.py
The break Statement
Sometimes you donât know itâs time to end a loop until you get half way through the body. In that case you can use the break statement to jump out of the loop.
For example, suppose you want to take input from the user until they type done . You could write:
The loop condition is True , which is always true, so the loop runs until it hits the break statement.
Each time through, it prompts the user with an angle bracket. If the user types done, the break statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. Hereâs a sample run:
This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (âstop when this happensâ) rather than negatively (âkeep going until that happensâ).
Note that the break statement works with the for loop as well.
The continue Statement
The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.
Let us examine the following example (save as continue.py ):
# user is to enter a string of at minimum 3 words # to end the user is to enter the word 'quit' while True: data = input('Enter at least 3 words: ') if data == 'quit': break if len(data) < 3: print('Too small') continue print('Input (data) is of sufficient length') # Do other kinds of processing here...
Sample Output:
In this program, we accept input from the user, but we process the input string only if it is at least 3 words long or the user enters the word âquitâ. So, we use the built-in len function to get the length and if the length is less than 3, we skip the rest of the statements in the block by using the continue statement. Otherwise, the rest of the statements in the loop are executed, doing any kind of processing we want to do here. When the user enters the word â quitâ we exit the loop using the break statement, then end the program. This is an example of an input validation loop . In an input validation loop (commonly designed using the while loop) the program inspects user input before it is processed by the program and if input is invalid it prompts user to enter correct data.
Note that the continue statement works with the for loop as well.
The forâŚin Statement
The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. Recall that a sequence is just an ordered collection of items. Let us look at the following program, for.py .
for i in range(1, 5): print(i) else: print('The for loop is over')
This is what the output of the program looks like in the Python shell after it runs:
In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in range function.
What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number. For example, range ( 1,5 ) gives the sequence [1, 2, 3, 4] . By default, range takes a step count of 1 . If we supply a third number to range , then that becomes the step count. For example , range(1,5,2) gives [1,3] . Remember that the range extends up to the second number i.e. it does not include the second number.
The for loop then iterates over this range â for i in range(1,5) is equivalent to for i in [1, 2, 3, 4] which is like assigning each number (or object) in the sequence to i , one at a time, and then executing the block of statements for each value of i . In this case, we just print the value in the block of statements.
The general form of the range expression is range( begin,end,step ) where
- begin is the first value in the range; if omitted, the default value is 0
- end is one past the last value in the range; the end value is always required and may not be omitted
- step is the amount to increment or decrement; if the step parameter is omitted, it defaults to 1 (counts up by ones)
begin , end , and step must all be integer expressions; floating-point expressions and other types are not allowed. The arguments in the range expression may be literal numbers (like 10), variables (like x , if x is equal to an integer), and arbitrarily complex integer expressions.
The range expression is very flexible. Consider the following loop that counts down from 21 to 3 by threes:
for n in range(21, 0, -3): print(n, end=' ')
21 18 15 12 9 6 3
Thus range(21, 0, -3) represents the sequence 21;18;15;12;9; 3 .
The expression range(1000) produces the sequence 0;1;2; : : : ; 999.
The following code computes and prints the sum of all the positive integers less than 100:
sum = 0 # Initialize sum for i in range(1, 100): sum += i print(sum)
Remember that the else block is optional. When included, it is always executed once after the for loop is over unless a break statement is encountered.
So far we have used the for loop to iterate over integer sequences because this is a useful and common task in developing apps. The for loop, however, can iterate over any iterable object , such as a string .
We can use a for loop to iterate over the characters that comprise a string. The following program uses a for loop to print the individual characters of a string (printLetters.py ) .
word = input('Enter a word: ') for letter in word: print(letter)
Sample output :
Practice 1 : Write a program to solve the following problem. [printWords.py]
# Ask the user how many words they want to enter # then print the words together on one line. sentence = "" num = input("How many words do you want to enter? ") try: num=int(num) except: print ("ERROR: enter a number") else: if num > 0: #check for a positive number for i in range(num): word = input("enter a word: ") sentence = sentence + " " + word print(sentence) else: print("Will only accept a positive integer number. Ending program")
Note the error checking performed in the program:
- Ensures the user only enters integer numbers as input
- Ensures the user enters a positive integer
Practice 2 : Write a program to solve the following problem. [numWords.py]
Unlike the example where we use d a for loop to iterate over the characters of a word, we need to use a string objectâs method to break the string into words. When you need to break a large string down into smaller chunks, or strings , you use the split() string method. By default, split() takes whitespace as the delimiter. Try executing this program (numWords.py)
Example output:
Once you have used split to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list.
Enhance this program to loop through each word in the list named words and print each word in uppercase on its own line ( uppercaseWords.py .
How to choose between the for and while loop?
Use a for loop if you know, before you start looping, the maximum number of times that youâll need to execute the body. For example, if youâre traversing a list of elements, you know that the maximum number of loop iterations you can possibly need is âall the elements in the listâ. Or if you need to print the 12 times table, we know right away how many times the loop will need to run.
So any problem like âiterate this weather model for 1000 cyclesâ, or âsearch this list of wordsâ, âfind all prime numbers up to 10000â suggest that a for loop is best.
By contrast, if you are required to repeat some computation until some condition is met, and you cannot calculate in advance when (of if) this will happen, as we did in this 3n + 1 problem, youâll need a while loop.
We call the first case definite iteration â we know ahead of time some definite bounds for what is needed. The latter case is called indefinite iteration â weâre not sure how many iterations weâll need â we cannot even establish an upper bound!
Nested Loops
Just like with if statements, while and for blocks can contain arbitrary Python statements, including other loops. A loop can therefore be nested within another loop. To see how nested loops work, consider a program that prints out a multiplication times tables ( multiplication.py ).
#multiplcation tables try: table = int(input("which multiplication times table do you want to print? (choose from 1 to 12) â)) x = table except: print("ERROR: enter a whole number") else: if table > 0 and table < 13: for y in range(1, 13): print (x,'*', y,'=', x*y) else: print ("ERROR: multiplication tables can be generated from 1 to 12 only")
Let us examine more closely the code in this program.
Now let us consider adding to this program to generate all the multiplication times tables from 1 to 12. This is easily done with nested loops.
#multiplcation times tables tables for x in range(1, 13): for y in range(1, 13): print (x,'*', y,'=', x*y)
The output after execution of this 3-lines-of-code program generates 144 lines of output!
1 * 1 = 11 * 2 = 21 * 3 = 31 * 4 = 41 * 5 = 51 * 6 = 61 * 7 = 71 * 8 = 81 * 9 = 91 * 10 = 101 * 11 = 111 * 12 = 122 * 1 = 22 * 2 = 42 * 3 = 62 * 4 = 82 * 5 = 102 * 6 = 122 * 7 = 142 * 8 = 162 * 9 = 182 * 10 = 202 * 11 = 222 * 12 = 24...12 * 1 = 1212 * 2 = 2412 * 3 = 3612 * 4 = 4812 * 5 = 6012 * 6 = 7212 * 7 = 8412 * 8 = 9612 * 9 = 10812 * 10 = 12012 * 11 = 13212 * 12 = 144
Basic File Processing
While a program is running, its data is stored in random access memory (RAM) on the computer it is execution on. RAM is fast and inexpensive, but it is also volatile, which means that when the program ends, or the computer shuts down, the data in RAM disappears. To make data available the next time the computer is turned on and the program is started, it has to be written to a non-volatile storage medium, as a file. By reading and writing files, programs can save information between program runs.
So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files.
For our purposes, we will assume that our data files are text filesâthat is, files filled with characters. The Python programs that you write are stored as text files as are any HTML webpage files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents. Note that text files have an End-Of-Line (EOL) character to indicate each lineâs termination.
Reading and Writing Text Files
In Python, we must open files before we can use them and close them when we are done with them. As you might expect, once a file is opened it becomes a Python object just like all other data. The following table shows the functions and methods that can be with files.
Table 7: File Functions and Methods
Python file object attributes provide information about the file and file state. The following table shows how to identify some of the objectâs attributes.
Table 8: File Object Attributes
The statement
file1 = open('myfile.txt', 'r')
creates and returns a file object in the variable named file1 . The first argument to open is the name of the file, and the second argument is a mode (in this example the mode is to read the file). This statement will attempt to read the content of the text file named myfile.txt . If the file does not exist or the user of the program does not have adequate permissions to open the file, the open function will raise an exception.
print(âERROR: unable to open or locate the fileâ)
# Do other kinds of processing here...
Similar to handling an error of invalid user input we need to use the try-except-else block to handle trying to read from a file which does not exist The following is an example:
file2 = open('myfile.txt', 'w')
creates and returns a file object in the variable named file2 which will write data to the text file named myfile.txt . If the file does not exist, the function creates the file on disk; no exceptions are raised when writing to a file. If a file by that name currently exists, new data will replace the current data stored in the file. This means any pre-existing data in the file will be lost.
Once you have a file object capable of writing (opened with âwâ) you can save data to the file associated with that file object using the write method. For a file object named file2 , the statement
file2.write('data')
stores the string âdataâ to the file. The three statements
file2.write('compute')
file2.write('process')
writes the text 'datacomputeprocess' to the file. If our intention is to retrieve the three separate original strings, we must add delimiters to separate the pieces of data. Newline characters serve as good delimiters:
file2.write('data\n')
file2.write('compute\n')
file2.write('process\n')
This places each word on its own line in the text file. The advantage of storing each piece of data on its own line of text is that it makes it easier to read the data from the file with a for statement. If file2 is a file object created for reading, the following code:
for line in file2:
print(line.strip())
reads in each line of text from the file and prints it out. The variable line is a string, and we use the strip method to remove the trailing newline ( '\n' ) character.
We also can read the contents of the entire file into a single string using the file objectâs read method:
contents = file2.read()
Given the text file from above, the code
in = open('compterms.txt', 'r')
str = in.read()
assigns to str the string 'data\ncompute\nprocess\n' .
The open method opens a file for reading or writing, and the read , write , and other such methods enable the program to interact with the file. When the executing program is finished with its file processing it must call the close method to close the file properly. Failure to close a file can have serious consequences when writing to a file, as data meant to be saved could be lost. Every call to the open function should have a corresponding call to the file objectâs close method.
Practice â Following are two simple programs designed to write data to a file and then read and print each line of a file. Try entering, saving and running the following programs ( writeFile.py and readFile.py ).
Figure 49: writeFile.py
Figure 50: readFile.py
This is the output after running this program:
We can also read and process each line of data in a file by using the readline() method. Try entering, saving and running the following programs (readFile2.py) . The output is the same.
try: file1 = open('compterms.txt','r') # try to find & open the file except: print('ERROR: unable to open or locate the file') else: line = file1.readline() # Read the first line while line: # Enter the loop as long as there is a line of data to read print(line.strip()) # Remove trailing newline character and print the line line = file1.readline() # Read the next line file1.close() # Close the file after processing data
Processing âBig Dataâ
Big data is large, and often times complex, data sets that need to be processed into useful information. Python has emerged over the past few years as a leader in data science programming including the analysis and visualization of large data sets.
Data sets grow rapidly â in part because they are increasingly gathered by cheap and numerous information-sensing internet of things devices such as mobile devices, aerial (remote sensing), software logs, cameras, microphones, radio-frequency identification (RFID) readers and wireless sensor networks. The worldâs technological per-capita capacity to store information has roughly doubled every 40 months since the 1980s; as of 2012, every day 2.5 exabytes (2.5Ă1018) of data are generated. Based on an IDC (International Data Corporation) report prediction, the global data volume will grow exponentially from 4.4 zettabytes to 44 zettabytes between 2013 and 2020. By 2025, IDC predicts there will be 163 zettabytes of data. [1]
Figure 51: âData Informationâ(www.maxpixel.net/Circle-Know-Arrangement-Data-Information-Learn-229113) is licensed under CC-BY 0
An example of a successful business that uses python for collecting and analyzing data is ForecastWatch. ForecastWatch.com is in the business of rating the accuracy of weather reports from companies such as Accuweather, MyForecast.com, and The Weather Channel. Over 36,000 weather forecasts are collected every day for over 800 U.S. cities, and later compared with actual climatological data. These comparisons are used by meteorologists to improve their weather forecasts, and to compare their forecasts with others. They are also used by consumers to better understand the probable accuracy of a forecast. [2]
We will use real data from open source data sets (that is saved as text files) for programming practice.
Problem Statement : Using the text file, NYScoastalFlooding.txt , identify each of the New York State counties (zones) effected by coastal flooding during the month of August within the dataset provided.
The first step in finding a solution for this problem is to review and understand the format of the data set provided. Open the text in a text editor and note the field headings in the first line of the file. The following is a small sample from the NYScoastalFlooding.txt file.
We see that the data set has six fields:
- year: Four digit year for the event in this record
- month_name: Name of the month for the event in this record (spelled out; not abbreviated)
- event_type spelled out; not abbreviated
- cz_type: Indicates whether the event happened in a (C) county/parish, (Z) zone or (M) marine
- cz_fips: The county FIPS number is a unique number assigned to the county by the National Institute for Standards and Technology (NIST) or NWS Forecast Zone Number
- cz_name: County/Parish, Zone or Marine Name assigned to the county FIPS number or NWS Forecast Zone
We also notice that all but the first field on each line has a blank space before it (this is important!).
We will break this problem into smaller pieces. Let us start with a program that reads each of the records and keeps a count of the number of records in the file (dataRecordNumb.py). This program is a modification of our readFile.py program.
try: file1 = open('NYScoastalFlooding.txt ','r') # try to find & open the file except: print('ERROR: unable to open or locate the file') else: count = 0 # Initialize recount cout to zero for line in file1: # Read each line as text print(line.strip()) # Print the record count = count + 1 # increment record counter print("There are",count,"data records in this file") file1.close() # Close the file after processing data
The last line of the output from running this program:
Recall from Unit 2 when we used the split() method to identify each individual word in a sentence. What the method does is split or breakup a string and add the data to a list of separate âchunksâ using a defined separator. So if this line is read
2017, January, Coastal Flood, Z, 79, NORTHEAST SUFFOLK
and we split the line into individual fields we could identify those records effected by coastal flooding during the month of August.
fields = line.split(â,â)
If we now print fields we have a list of all the fields which we can now access.
>>> print(fields)
['2017', ' January', ' Coastal Flood', ' Z', ' 79', ' NORTHEAST SUFFOLK']
Notice the extra blank space before the string âJanuaryâ in the list fields . When trying to identify those records with the string âAugustâ the extra space must be dealt with!
Let us complete the second program to solve the problem of identifying (and print) each of the New York State counties (zones) effected by coastal flooding during the month of August ( NYScountiesAug.py ).
# identify each of the New York State counties (zones) effected by coastal flooding during the month of August print("The following are the NYS counties (zones) effected by coastal flooding during the month of August:") try: file1 = open('NYScoastalFlooding.txt ','r') # try to find & open the file except: print('ERROR: unable to open or locate the file') else: for line in file1: # Read each line as text fields = line.split(",") # split each line into a list of 'fields' if fields[1] == " August": # check if the 2nd field is August county = fields[5] # identify the county from the 6th field print(county.strip()) # Print the record file1.close() # Close the file after processing data
The output from running this program:
To test if the program correctly identified all records effected by coastal flooding during the month of August you would need to manually go through each of the 61 records and flag the records that should be found and printed (or use an app such as Excel to do a sort and count for you).
The actual data set I downloaded had a total of 56,921 records and 51 different fields (a lot more data than what we just worked with!). A professional data scientist would also test her program using a subset of the large data set until she could be satisfied that the program was running correctly and producing the correct results.
Unit Summary
Practice problems.
- Write a program to accept a number from the user and print whether it is positive or negative.
- Accept three numbers from the user and print the greatest number.
- Write a program that accepts a number in the range from 1 to 7 from the user and generates and displays the name of the weekday.
- Write a program to input 5 numbers from the user and calculates and displays their sum and average.
- Write a program that accepts an integer number and indicates whether it is negative, zero, or positive. Force the user to enter only valid data (repeatedly ask the user to enter only an integer number)
- range(5, 10)
- range(5, 20, 3)
- range(20, 5, -1)
- range(20, 5, -3)
- range(10, 5)
- range(10, 101, 10)
- range(10, -1, -1)
- range(-3, 4)
- range(0, 10, 1)
- Write a program to print a pattern like a right angle triangle with numbers where each number will repeat in a row. The pattern is as follows: 1 22 333 4444 55555
- Find a poem you like and save it as a text file named poem.txt. Write a program that counts the number of lines in your program. Print out the line count and each individual line in the program (no extra blank lines!)
- Write a program that stores the first 100 integers to a text file named numbers.txt. Each number should appear on a line all by itself.
- Write a program to find the longest word in a text file.
- Wikipedia contributors. "Big data." Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 4 Jul. 2018. Web. 12 Jul. 2018. âľ
- Python Software Foundation. Python Success Stories, https://www.python.org/about/success/forecastwatch/ . Accessed July 12, 2018 âľ
Privacy Policy
- Programming
Sequence, Selection, and Iteration – The Building Blocks of Programming Languages
- Posted by Frank J. Mitropoulos
- Categories Programming
- Date August 31, 2018
- Comments 34 comments
There are many, many programming languages available that allow us to program computers to solve all kinds of problems. There are scripting languages, systems languages, web programming languages, dynamic languages, object-oriented languages, functional languages, and the list goes on and on. Â
But did you know that all programming languages have 3 elements in common? Three very simple elements that give us the power to implement solutions to extremely complex problems. Â
These 3 elements are: Â
- Â Sequence Â
Selection Â
Iteration  .
Sure, many programming languages have many other complex features. Some are âeasyâ to learn and others more difficult to learn. Â
In this post I’d like to talk about each one of these elements and build a very simple C++ program that uses all of them. C++ is one of those languages that is considered very difficult to learn because it is very complex. Â
Letâs talk about each of these elements individually and weâll write a simple C++ program along the way that uses all of them. Weâll keep this example simple and Iâm sure you will be able to follow along. Â
If youâd like to follow along by typing or copying/pasting the code below, you can do so without installing any software at all. Simply point your favorite browser to https://www.onlinegdb.com/   and select C++17 from the dropdown list at the upper right.
Then delete the text in the online editor window and type or copy/paste the code weâll write along the way. Â
When you are ready to run the program, simply click on the green Run button at the top of the screen. Â
If you see any errors, then double check that you entered the code exactly as shown and try it again. Once the program runs, you will be able to enter data and see output at the bottom of the screen.
So, what are these 3 elements all about?
Itâs actually very simple. In order to solve problems with any programming language, we write code that tells the computer what operations to execute and in what order. The order must be very specific – remember the computer is not very smart – it simply follows our instructions. These operations make up what is called an algorithm . Just a fancy word that describes a set of operations that solves a specific problem. You can think of this very much like a cooking recipe. If you follow the recipe exactly, you will end up with the produce of that recipe.
Sequence , Selection , and Iteration are the basic elements that we use to tell the computer what to do. The code will definitely look different depending on the programming language we use, but the algorithm will be the same.
So letâs describe these elements:
- Sequence – the order we want the computer to execute the instructions we provide as programmers. For example, do this first, then do this, then do that, and so forth.
- Selection – selecting which path of an algorithm to execute depending on some criteria. For example, if you passed a class in school, then we execute the operations that clap and cheer and play a song. But if you didnât pass the class, then maybe we would say, âBetter luck next time, hang in there!â
- Iteration – looping or repeating. Many times, we want to be able to repeat a set of operations a specific number of times or until some condition occurs.
Thatâs it, these 3 super simple elements give us the ability to write programs that solve problems. When we put them together we can create programs that are very complex such as operating systems, game engines, compilers, anything! In fact, with just Sequence , Selection , and Iteration  we can implement any algorithm.
Read that again! Any algorithm! Thatâs a very powerful place to be!!
Alright, letâs write some C++ code together.
Letâs start with Sequence. Most programming languages simply execute instructions one after another as they are read â much like reading a recipe or a book. Â
Hereâs a simple C++ program that prompts the user to enter their age and then reads what they type in on the keyboard into a variable and then displays âBye.â to the display console. Â
All programming language have structure and syntax that we have to follow so that the program is legal, but thatâs not important right now. So donât worry about the details of the code, letâs focus on the big picture . The code on lines 7, 8, and 9 are what we are interested in. Whatâs important is that you can see the order or Sequence  of the operations:
- We prompt the user to enter their age
- We read the integer they entered and store it in a variable named age
- We display “ Bye. “
Run this program several times and enter different ages. Make sure you enter a whole number since thatâs what the program expects.
Pretty boring right? Yes, but the computer is doing exactly what we are telling it to do.
That was pretty easy. But if we were only limited to Sequence  our programs would be very limited indeed. We have to have a way to make decisions based on certain conditions.
Now letâs modify this program so that it can decide whether a person can vote! Weâll assume that a person must be 18 years or older to vote. Â
So, letâs see how Selection  works. Â
Weâll add logic so that if the age entered is 18 or greater then  the program will display, “ You can vote.” and if the age entered is less than 18 then the program will display, “ Sorry, you canât vote.” . Â
See the selection, we are selecting which operations to execute depending on what the value of age is. Pretty simple and useful too! Â
Letâs do it. Â
Notice that on line 10 we added an if statement. If the expression in the parentheses is true then we display, “ You can vote. “ Â
But what if the personâs age is not greater than 18? Thatâs where the else on line 12 comes in. In this case we display, “ Sorry, you canât vote yet. “ . We made a yes/no or true/false decision and we selected  the operations to execute based on that decision. Â
That was pretty easy . Notice how we combined Sequence  and Selection  to make our program more useful. Â
But, suppose there are 3 voters and we would like to ask each of them what their age is. We could copy and paste the code 3 times, right? Sure, but if we had 1000 voters the program would grow very large and become very hard to follow and change. Thatâs where Iteration  comes in. We can use a loop to iterate  3 times. Programming languages all allow Iteration  and many provide multiple ways to iterate . Letâs do it using a very simple for loop in C++.Â
So  let’s rewrite the code one final time. Â
Notice that our original code is still there, we havenât changed it. But we now added a new operation on line 7 that tells the program to count from 1 to 3 and execute everything from lines 9-15 that many times. Â
So, now we will be asked to enter the ages for 3 voters and each time weâll know whether a voter can vote or note. Pretty cool! Â
Now our program is using Sequence  to provide the order in which we execute our instructions. Selection  to allow decisions to be made and Iteration  to loop or repeat our instructions as many times as we need. Â
Congratulations !
You have just learned the 3 elements that all programming languages must support and you wrote a simple program in one of the most complex programming languages used today, C++.
We can combine these 3 simple elements to implement any algorithm â now thatâs power!
Of course, there is much more to programming. As our problems grow larger and more complex, we need other elements to help us deal with the complexity. Some of these elements are classes, methods, functions, threads, and many others.
But remember, the core elements of programming are the simple, Sequence , Selection , and Iteration elements that we learned about â thatâs what itâs all about!
Ready to learn more? Take a look at my Beginning C++ Programming – From Beginner to Beyond course.  It’s got close to 40 hours of video training and is aimed to make you a competent C++ programmer. It’s one of the most popular courses of it’s kind on Udemy!
Previous post
Do You Need A College/University Degree To Get A Programming Job?
How microsoft is enabling developers to build native ios and android apps, you may also like, the complete javascript course for developers.
Recently a student in my The Complete JavaScript Course for Developers course asked about the capabilities and limitations of JavaScript. Specifically, can JavaScript collect and handle data from a user in a mobile environment. The answer is an unequivocal âyesâ …
Java 11 has Arrived. Is it time to panic?
Kotlin â Java Developers Have a Head Start
Leave A Reply Cancel reply
Your email address will not be published. Required fields are marked *
- No results found
Use four logic structures: Sequential structure Decision structure Loop structure Case structure
Share "Use four logic structures: Sequential structure Decision structure Loop structure Case structure"
Academic year: 2020
Loading.... (view fulltext now)
UNIT â I PART - B
Introduction to Programming Structure
⍠Objectives:
⪠Explain the need for structural programming
⪠Explain how to design modules and functions, in terms of cohesion and coupling
⪠Explain the difference between local and global variables
⪠Explain the use of parameters
Pointers for Structuring a Program
⍠Use four logic structures:
⪠Sequential structure
⪠Decision structure
⪠Loop structure
The Modules and Their Functions
⍠Use modules
⍠Eliminate the rewriting of identical processes by using modules.
⍠Use techniques to improve readability, including the four logic structures, proper naming of variables,
Modules and Their Functions
⍠Rules for designing modules:
⪠Each module is an entity in itself.
⪠Each module should have a single function. (eg: printing, calculating etc.)
⪠Each module should be small enough to be easily read and modified.
⪠The length of a module is governed by its function and the number of instructions to be executed to perform that
Types of Modules
⍠Control Module : shows the overall flow of data through the program.
⍠Initialization Module: processes instructions that are executed only once during the program and only at the beginning.
⍠Process Module: (Processed by once or Loop)
⪠Calculation Modules
⪠Print Modules
⪠Read and Data Validation Modules
⍠Wrapup module: process all instructions that are executed only once during the program and only at the end (closing file, Printing Totals)
Cohesion and Coupling
⍠Most difficult task in development of a solution to a problem is to divide the solution into modules
⍠Question arise what should be included in each module
⍠Modules should be independent and perform single task
⍠Cohesion is the ability for a module to work independently from all other modules.
⍠Coupling is accomplished by some type of interface between modules that enables data to be passed from one module to another with minimum interruption.
⪠Cohesion allows programmer to write module of a larger program and test it independently.
⍠Example Calculate the Income Tax
⍠Input Total Income
⍠Calculate the Tax
⍠There are three ways to couple modules:
⪠Global variables
⪠Parameters
Local and Global Parameters
⍠Local variables are used only by the module itself.
⪠Cohesion is achieved
⍠Global variables are used by all the modules.
⪠Used for coupling
⍠Parameters are one of the hardest & most important concepts to understand & to use in programming.
⍠Each section of the module is developed as cohesive module, coupled together thru parameters.
⍠Parameters are local variables that are passed or sent from one module to another.
⍠Eg: read(a, b, c)
⍠The calling module is the module that processes another module.
⍠The called module is the module being processed.
⍠The actual parameter listing is the list of parameters that follows the module name being processed in the calling module.
Controlpay //calling module process read (*hours,*payrate)
process calx(hours,payrate,*pay) actual parameters process print(pay)
Read(*hrs,*rate) formal parameters listings Enter hrs,rate
Calc(hrs,rate,*pay) formal parameters pay=hrs*rate
Print(pay) formal parameters Print pay
⍠There are two ways to send data from one module to another through the use of parameters:
⍠Call-by-value:
⪠No asterisk in front of variable
⪠Separate memory location
⍠Call-by-reference:
⪠Asterisk symbol in front of variable
Return Values
⍠Functions return values when used within another
instruction.
⍠The return value is the result of the function.
⍠The value is only sent out of the called module into
Variable Names and Data Dictionary
⍠Data dictionary helps to keep track of the variable usage in the program.
⍠It contains:
⪠Variable names
⪠Data types
⪠The module in which they are found
⪠Pseudonyms
⪠Module in which pseudonyms are found
Data Dictionary
Item Variable Name
Module Scope Pseudon ym /Module Error Check Hours Worked
Hours Numeric - real
Control Pay
Local Hrs None
Hours Worked
Hrs Numeric - real
Read / Calc
Parameter Hours Hours < 0
Pay Rate PayRate Numeric â real
Local Rate None
Pay Rate Rate Numeric â real
Parameter PayRate Pay rate < 4.00
Net Pay Pay Numeric â real
Local None None
Net Pay Pay Numeric - real
Calc / Print
Four Logic Structures
⍠Logic structure control the logic of the data flow through
the module.
⍠The instructions and the flowcharts are combinations of
four logic structures.
Problem Solving with Sequential Logic Structure
⪠Use of the sequential logic structure to develop a solution to a problem
⪠Use the proper form for instructions in an algorithm and a flowchart.
Sequential Logic Structure
⍠Simplest logical structure.
⍠Algorithms and flowcharts are used to represent the
⍠An algorithm begins with the start instruction,
executes all the instructions sequentially and ends
Flowchart for Sequential Structure
1. Enter Name, Age
2. Print Name, Age
Enter Name, Age
Print Name, Age
Solution Development
⍠The organizing tools are used in the six steps of problem solving.
⪠Problem Analysis Chart: helps in defining and understanding the problem, develop ideas for solution and select the best solution.
⪠Interactivity chart: breaks the solution to the problem into parts.
⪠IPO Chart: helps define the input, the output, and the processing steps.
⪠The coupling diagram and the data dictionary : designates the data flow between the modules. The data dictionary records the information on the items.
⪠The algorithms define the steps of the solution.
⍠Problem: Mary Smith is looking for the bank that will
give the most return on her money over the next five years. She has $2000 to put into a saving account.
⍠The standard equation to calculate principal plus interest at the end of a period of time is:
Amount = P * ( 1 + I/M ) ^ (N * M)
Where P = Principal amount
I = Interest
N = Number of years
Problem Analysis
Given Data Required Results
Principal - $ 2,000 Interest
Number of Years - 5 Compound Interval (#/year)
Principal plus Interest at the end of the time period
Required Processing
Amount = P * (1 + I/M) ^ (N * M)
Solution Alternatives
1. Enter all data as variables *
2. Enter principal and interest as constants and the other data as variable
3. Process one bank in one run * 4. Process all banks in one run
The Interactivity Chart
⍠The problem is broke into four modules:
⍠The InterestControl Module
⪠Which controls the solution
⍠The Read Module
⪠Which enters the data
⍠The Calc Module
⪠Which calculates the amount
⍠The Print Module
Interactivity Chart
InterestControl
Input Processing Module
1. Beginning Principal 2. Interest Rate 3. Number of
4. Number of Times
Interest is Compounded Yearly
1. Enter Data (Change interest rate to
2. Calculate ending
principal and interest Amount = prinicipal * ( 1 +
interest / time) ^ ( years * time)
1. Print required results
Read Calc Print 1. Ending Principal plus interest 2. All input
Coupling and Data Dictionary
Modules Scope Pseudonym /module
Error check
Principal Principal Numeric - real
InterestControl/ Read/Calc/Print
Parameter None None
Interest Interest Numeric - real
Number of years Years Numeric - real InterestControl/ Read/Calc/Print Local
ing Time Time
Numeric - real
Amount Amount Numeric - real
Internal and External Documentation
⍠Documentation highlights the important details about the program.
⍠Internal Documentation is accomplished through the use of remark or comment statements.
⍠External documentation involves writing manuals with detailed explanation of the program and how to use it.
⍠Documentation can be done while developing
Algorithm and Flowchart for InterestControl Module
Algorithm Flowchart Annotation Test
1. Process Read
(*P, *I, *Y, *T)
2. Process Calc ( P, I, Y, T, *Amount)
3. Process Print (P, I, Y, T, Amount)
Enters all data from keyboard
Calculates amount
Prints data and amount
2. Transfer to Read
3. Transfer to Calc
4. Transfer to Print
Internal Documentation External Documentation
1. Calculates principal and interest given, beginning principal, interest rate,
number of years and compounded time interval
2. Include annotations
Same as 1 in Internal Documentation
Algorithm and Flowchart for Read Module
Read ( *P, *I, *Y, *T)
1. Enter P, I, Y, T
2. I = I / 100
1. Interest is Rate
2. Time is number of times interest is compounded yearly P I Y T
1. Remark at top: Module to enter all data and to convert interest rate
1. Explain input Data
Enter P, I, Y, T
Algorithm and Flowchart for Calc Module
Calc(P, I, Y, T,*A)
1. A = P * (1 + I/T) ^ (Y * T)
2. End None
(1+0.1/2)^(5*2)
A = 2000 * (1 + 0.05)^10
A = 3257.78
1. Remark at top: Module to enter all data and interest
1. Specify equation
A = P * (1 + I/T) ^ (Y * T)
Algorithm and Flowchart for Print Module
Print ( P, I, Y, T, A)
1. Print A, I, Y, T and A
1. Print each variable on a
separate line with a label
Print what is required
1. Remark at top: Module to print required output
1. Specify output
Problem Solving with Decisions
⪠Develop problem using the decision logic structure in conjunction with the sequential logic structure.
⪠Use the seven problem solving tools when developing a solution using the decision logic structure.
⪠Use nested decision instructions to develop a problem solution.
⪠Distinguish the different uses of straight through positive and negative nested decision logic structures.
⪠Convert a positive decision logic structure to a negative decision logic structure.
⪠Develop decision tables given a set of policies.
Decision Logic Structure
⍠The decision logic structure uses the If/Then/Else instruction.
⍠If the condition is true then execute a set of
instructions else execute another set of instructions
⍠Structure:
If < Condition(s) > Then
<True Statements> Else
Flowchart for Decision Structure
<Condition(s)>
Instruction set
Simple Decision Statement
If Hours > 40 then Pay = Rate *
(40+1.5*(Hours-40))
Pay = Rate * Hours
Pay = Rate * ( 40 + 1.5 * ( Hours â 40))
If Hours > 40
Multiple If/Then/Else Instructions
⍠There are three types of decision logic:
⍠Straight â through logic
⪠All of the decisions are processed sequentially one after the other.
⪠There is no else part of the instructions
⍠Positive logic
⪠Allows the flow of processing to continue through the module instead of succeeding decisions, once the resultant of a decision is true.
⍠Negative logic
If PayType = âHourlyâ then If Hours > 40 then
Pay = Rate * (40 + 1.5 * ( Hours â 40 )) Else
Pay = Rate * Hours Else
If PayType = Hourly
Pay = Salary
Pay = Rate * Hours Pay = Rate * ( 40 + 1.5 * (Hours â 40)
Using Straight through Logic
⍠All conditions are tested
⍠Least efficient because all the decision must be
⍠Used in combinations with other two logic types and
⍠Problem: Find the amount to charge people of varying ages for a concert ticket. When the person is under 16, the charge is $7, when the person is 65 or over, the
charge is $5, all others are charged $10.
⍠The conditions are the following:
Age Charges
Age < 16 7
Age >=16 & Age <65 10
Algorithm If Age < 16 then
If Age > = 16 and Age < 65 then
Charge = 10
If Age >= 65 then
Using Straight through Logic Flowchart
If Age < 16
If Age >16 and Age < 65
If Age >= 65
Positive Logic
⍠The computer follow a set of instructions and
continue processing if the condition is true.
⍠If the condition is not true then the computer
processes another decision.
⍠Positive logic always uses nested If/Then/Else
Example Positive Logic
⍠Sale Commission
⍠<=2000 0.02
⍠2001-4000 0.04
⍠4001-6000 0.07
Negative Logic
⍠Negative logic is the hardest to comprehend because
of negative terms.
⍠If the decision is false the computer processes
instructions and continues processing.
⍠When the decision is true the computer processes the
Example Negative Logic
Logic conversion.
⍠To convert positive logic to negative logic or vice versa do the following:
⪠Change all < to >=
⪠Change all <= to >
⪠Change all > to <=
⪠Change all >= to <
⪠Change all = to <>
⪠Change all <> to =
Which Decision Logic
To analyze which type of decision logic is to, be used consider following questions:.
⪠Which type would make the solution most readable?
⪠Which type would make the solution the easiest to maintain or change?
⪠Which would require the fewest tests when you donât know anything about the data?
⍠Straight Through Logic
⍠Negative Logic
⍠Positive Logic
⍠Conversion Type
Home Work examples
⍠Draw positive and negative logic for following conditions.
⍠bonus=10 when pay<=1000
⍠Bonus=50 when 1000 < pay<=2000
Problem Solving with Loops
⪠Develop problems using the loop logic structure in conjunction with the decision and sequential logic structures.
⪠Use of seven problem solving tools to solve a problem using the loop logic structure.
⪠Use counters and accumulators in a problem solution.
⪠Use nested loop instructions to develop a problem solution
⪠Distinguish the different uses of three types of loop logic structures.
The Loop logic structure
⍠There are three types of loop structures:
⪠While/WhileEnd loop
Repeats instructions while a condition is true and stops repeating
when a condition is false.
⪠Repeat/Until loop
Repeats instructions while a condition is false or until a condition
⪠Automatic â counter loop
Variable is set as counter and the instructions are repeated till the
Tasks to be accomplished
⍠Counting ( Incrementing and Decrementing)
⪠Adding a constant to the value of a variable
Eg: counter = counter + 1
⪠For decrementing add a negative value.
Eg: counter = counter + (-1)
⍠Accumulating (summing a group of numbers)
⪠Adding a variable to the value of another variable
Eg: sum = sum + variable
While/WhileEnd
⍠While the condition is true, repeat all instructions between the while and whileEnd.
⍠Algorithm:
While < Condition(s) > Instruction
Instruction âŚ..
⍠Flowchart:
Instruction
Decision equivalent to While/WhileEnd
Algorithm Flowchart
If <Condition(s) >
PIAT (Putting It All Together)
Problem: create the algorithm and the flowchart, to find the average age of all the students in a.
⪠Calculates the average age in the class taking the age
of all the students as input.
Repeat/Until Loop
⍠Repeat the set of instructions between the repeat and until, until a condition is true.
⍠Two major difference with While/WhileEnd
⪠In While/WhileEnd the program continues the loop as long as the condition is true whereas in Repeat/Until loop the program
stops the loop process when the resultant of the condition is
⍠Format of Repeat/Until algorithm is: Repeat
Instruction Instruction âŚ..
⍠Flowchart A
Automatic â Counter Loop
⍠A variable value is incremented or decremented each time the loop is
⍠Counter variable is initialized with some starting value.
⍠The loop repeats until the counter is greater than an ending number.
Loop : Counter = Begin to End step s
Begin End Step
Rules for Automatic Counter Loop
⍠For incremental loop:
⪠When the computer executes the loop instruction it sets the counter equal to the beginning number.
⪠When the computer executes the loop end, it increments the counter.
⪠When the counter is less than or equal to the ending number, the processing continues at the instruction that follow the loop
instruction. When the counter is greater than the ending number, the processing continues at the instruction that follows the loop-end instruction.
⍠For decremented loop:
⪠Counter is decremented instead of incremented at the end of the loop.
⪠Algorithm and flowchart using Automatic counter
Nested Loops
⍠Loops can be nested like decisions.
⍠Each loop is nested inside the loop just outside it.
⍠The inner loop does not have the same types of loop
structures as the outer loop.
⍠Example of nested loops:
⪠Nested loop using while/WhileEnd and Repeat/Until
⍠Indicators are the logical variables that a programmer
sets within a program to change the processing path or to
control when the processing of a loop should end.
⍠Eg: flags, switches or trip values.
⍠An error indicator designates that an error has occurred
in the input or the output. (eg: true or false)
⍠An end-of-data indicator designates that there is no more
⍠Recursion occurs when a module/function calls itself.
⍠The condition that ends the loop must be within the
⍠Recursive procedures can be replaced by conventional
loop structures.
⍠Example of Recursion
Problem Solving with Case Logic Structure
⪠Develop problems using the case logic structure in conjunction with the loop, decision and sequential logic structure.
The Case Logic Structure
⍠Case logic structure is made of several or many set of
instructions one of which will be selected by the user and
executed by the programmer.
⍠It does not enable the program to loop back to select
another option.
⍠Format of Case logic structure: Case of variable
= CONSTANT 1:
Actions for variable = CONSTANT 1
=CONSTANT 2:
Actions for variable = CONSTANT 2
Actions for variable = anything else
⍠Problem 1: A company has four different medical plans. The programmer has given each plan a code corresponding to the beginning initial of the
Plan 1 = F, Plan 2 = B, Plan 3 = K and Plan 4 = E. The company pays for all of plan 1. The individual has to pay for the part of the others. The Payroll
deduction for Plan 2 = 4.65, for Plan 3 = 7.85 and for Plan 4 = 5.50. Any other codes are considered in
error. Write an algorithm and draw the flowchart for a module to determine the payroll deduction.
⍠Codes are some characters, character strings that a programmer uses to name the options, the constants
in a case structure.
⍠The major difference between indicators and codes are:
⪠Codes are data to be entered by the user. Indicators are internal signals to change the processing path.
⍠Problem 2: Calculate the employeeâs pay. The codes are as follows:
H = Hourly Pay = rate * hours
P = Piece work Pay = rate * number of pieces C = Commission Pay = commission * sales
S = Salary Pay = salary
Any other code will considered as error.
Related documents
University of Hull in the works of Willie Yeadon only.. Details of compilation of albums U DYE/1/2-135, with dates of compilation. Contains 210 mounted photographs with
The Japanese Employment System After the Bubble Burst , supra note 6, at 8 (â[T]he literature almost unanimously considers non-standard employment workers outside of the
Risk management, stakeholder management, resource management and intregation management are extremely important knowledge areas which project teams need to give
Similarly, among the various dehydrogenase systems characterized, NADH-dependent reductase has received special attention and has been shown to reduce metmyoglobin to deoxy-
The implementation of universal health care programs, particularly in Europe, has created a kind of social experiment to evaluate changes in health disparities with more equal
Despite national recognition of the need for pregnant women to be assessed and treated by acute physicians with training in obstetric medicine during an acute medical illness, there
The results for NRT advertising from the models with DMA locational fixed effects variables are preferred since NRT is measured at the DMA level.. However, the cigarette
According to Fonseca (1998), supported by the propositions of the Public Relations Society of America, the functions that delimit the work of a Public Relations professional are
How to master the seven-step problem-solving process
In this episode of the McKinsey Podcast , Simon London speaks with Charles Conn, CEO of venture-capital firm Oxford Sciences Innovation, and McKinsey senior partner Hugo Sarrazin about the complexities of different problem-solving strategies.
Podcast transcript
Simon London: Hello, and welcome to this episode of the McKinsey Podcast , with me, Simon London. Whatâs the number-one skill you need to succeed professionally? Salesmanship, perhaps? Or a facility with statistics? Or maybe the ability to communicate crisply and clearly? Many would argue that at the very top of the list comes problem solving: that is, the ability to think through and come up with an optimal course of action to address any complex challengeâin business, in public policy, or indeed in life.
Looked at this way, itâs no surprise that McKinsey takes problem solving very seriously, testing for it during the recruiting process and then honing it, in McKinsey consultants, through immersion in a structured seven-step method. To discuss the art of problem solving, I sat down in California with McKinsey senior partner Hugo Sarrazin and also with Charles Conn. Charles is a former McKinsey partner, entrepreneur, executive, and coauthor of the book Bulletproof Problem Solving: The One Skill That Changes Everything [John Wiley & Sons, 2018].
Charles and Hugo, welcome to the podcast. Thank you for being here.
Hugo Sarrazin: Our pleasure.
Charles Conn: Itâs terrific to be here.
Simon London: Problem solving is a really interesting piece of terminology. It could mean so many different things. I have a son whoâs a teenage climber. They talk about solving problems. Climbing is problem solving. Charles, when you talk about problem solving, what are you talking about?
Charles Conn: For me, problem solving is the answer to the question âWhat should I do?â Itâs interesting when thereâs uncertainty and complexity, and when itâs meaningful because there are consequences. Your sonâs climbing is a perfect example. There are consequences, and itâs complicated, and thereâs uncertaintyâcan he make that grab? I think we can apply that same frame almost at any level. You can think about questions like âWhat town would I like to live in?â or âShould I put solar panels on my roof?â
You might think thatâs a funny thing to apply problem solving to, but in my mind itâs not fundamentally different from business problem solving, which answers the question âWhat should my strategy be?â Or problem solving at the policy level: âHow do we combat climate change?â âShould I support the local school bond?â I think these are all part and parcel of the same type of question, âWhat should I do?â
Iâm a big fan of structured problem solving. By following steps, we can more clearly understand what problem it is weâre solving, what are the components of the problem that weâre solving, which components are the most important ones for us to pay attention to, which analytic techniques we should apply to those, and how we can synthesize what weâve learned back into a compelling story. Thatâs all it is, at its heart.
I think sometimes when people think about seven steps, they assume that thereâs a rigidity to this. Thatâs not it at all. Itâs actually to give you the scope for creativity, which often doesnât exist when your problem solving is muddled.
Simon London: You were just talking about the seven-step process. Thatâs whatâs written down in the book, but itâs a very McKinsey process as well. Without getting too deep into the weeds, letâs go through the steps, one by one. You were just talking about problem definition as being a particularly important thing to get right first. Thatâs the first step. Hugo, tell us about that.
Hugo Sarrazin: It is surprising how often people jump past this step and make a bunch of assumptions. The most powerful thing is to step back and ask the basic questionsââWhat are we trying to solve? What are the constraints that exist? What are the dependencies?â Letâs make those explicit and really push the thinking and defining. At McKinsey, we spend an enormous amount of time in writing that little statement, and the statement, if youâre a logic purist, is great. You debate. âIs it an âorâ? Is it an âandâ? Whatâs the action verb?â Because all these specific words help you get to the heart of what matters.
Want to subscribe to The McKinsey Podcast ?
Simon London: So this is a concise problem statement.
Hugo Sarrazin: Yeah. Itâs not like âCan we grow in Japan?â Thatâs interesting, but it is âWhat, specifically, are we trying to uncover in the growth of a product in Japan? Or a segment in Japan? Or a channel in Japan?â When you spend an enormous amount of time, in the first meeting of the different stakeholders, debating this and having different people put forward what they think the problem definition is, you realize that people have completely different views of why theyâre here. That, to me, is the most important step.
Charles Conn: I would agree with that. For me, the problem context is critical. When we understand âWhat are the forces acting upon your decision maker? How quickly is the answer needed? With what precision is the answer needed? Are there areas that are off limits or areas where we would particularly like to find our solution? Is the decision maker open to exploring other areas?â then you not only become more efficient, and move toward what we call the critical path in problem solving, but you also make it so much more likely that youâre not going to waste your time or your decision makerâs time.
How often do especially bright young people run off with half of the idea about what the problem is and start collecting data and start building modelsâonly to discover that theyâve really gone off half-cocked.
Hugo Sarrazin: Yeah.
Charles Conn: And in the wrong direction.
Simon London: OK. So step oneâand there is a real art and a structure to itâis define the problem. Step two, Charles?
Charles Conn: My favorite step is step two, which is to use logic trees to disaggregate the problem. Every problem weâre solving has some complexity and some uncertainty in it. The only way that we can really get our team working on the problem is to take the problem apart into logical pieces.
What we find, of course, is that the way to disaggregate the problem often gives you an insight into the answer to the problem quite quickly. I love to do two or three different cuts at it, each one giving a bit of a different insight into what might be going wrong. By doing sensible disaggregations, using logic trees, we can figure out which parts of the problem we should be looking at, and we can assign those different parts to team members.
Simon London: Whatâs a good example of a logic tree on a sort of ratable problem?
Charles Conn: Maybe the easiest one is the classic profit tree. Almost in every business that I would take a look at, I would start with a profit or return-on-assets tree. In its simplest form, you have the components of revenue, which are price and quantity, and the components of cost, which are cost and quantity. Each of those can be broken out. Cost can be broken into variable cost and fixed cost. The components of price can be broken into what your pricing scheme is. That simple tree often provides insight into whatâs going on in a business or what the difference is between that business and the competitors.
If we add the leg, which is âWhatâs the asset base or investment element?ââso profit divided by assetsâthen we can ask the question âIs the business using its investments sensibly?â whether thatâs in stores or in manufacturing or in transportation assets. I hope we can see just how simple this is, even though weâre describing it in words.
When I went to work with Gordon Moore at the Moore Foundation, the problem that he asked us to look at was âHow can we save Pacific salmon?â Now, that sounds like an impossible question, but it was amenable to precisely the same type of disaggregation and allowed us to organize what became a 15-year effort to improve the likelihood of good outcomes for Pacific salmon.
Simon London: Now, is there a danger that your logic tree can be impossibly large? This, I think, brings us onto the third step in the process, which is that you have to prioritize.
Charles Conn: Absolutely. The third step, which we also emphasize, along with good problem definition, is rigorous prioritizationâwe ask the questions âHow important is this lever or this branch of the tree in the overall outcome that we seek to achieve? How much can I move that lever?â Obviously, we try and focus our efforts on ones that have a big impact on the problem and the ones that we have the ability to change. With salmon, ocean conditions turned out to be a big lever, but not one that we could adjust. We focused our attention on fish habitats and fish-harvesting practices, which were big levers that we could affect.
People spend a lot of time arguing about branches that are either not important or that none of us can change. We see it in the public square. When we deal with questions at the policy levelââShould you support the death penalty?â âHow do we affect climate change?â âHow can we uncover the causes and address homelessness?ââitâs even more important that weâre focusing on levers that are big and movable.
Would you like to learn more about our Strategy & Corporate Finance Practice ?
Simon London: Letâs move swiftly on to step four. Youâve defined your problem, you disaggregate it, you prioritize where you want to analyzeâwhat you want to really look at hard. Then you got to the work plan. Now, what does that mean in practice?
Hugo Sarrazin: Depending on what youâve prioritized, there are many things you could do. It could be breaking the work among the team members so that people have a clear piece of the work to do. It could be defining the specific analyses that need to get done and executed, and being clear on time lines. Thereâs always a level-one answer, thereâs a level-two answer, thereâs a level-three answer. Without being too flippant, I can solve any problem during a good dinner with wine. It wonât have a whole lot of backing.
Simon London: Not going to have a lot of depth to it.
Hugo Sarrazin: No, but it may be useful as a starting point. If the stakes are not that high, that could be OK. If itâs really high stakes, you may need level three and have the whole model validated in three different ways. You need to find a work plan that reflects the level of precision, the time frame you have, and the stakeholders you need to bring along in the exercise.
Charles Conn: I love the way youâve described that, because, again, some people think of problem solving as a linear thing, but of course whatâs critical is that itâs iterative. As you say, you can solve the problem in one day or even one hour.
Charles Conn: We encourage our teams everywhere to do that. We call it the one-day answer or the one-hour answer. In work planning, weâre always iterating. Every time you see a 50-page work plan that stretches out to three months, you know itâs wrong. It will be outmoded very quickly by that learning process that you described. Iterative problem solving is a critical part of this. Sometimes, people think work planning sounds dull, but it isnât. Itâs how we know whatâs expected of us and when we need to deliver it and how weâre progressing toward the answer. Itâs also the place where we can deal with biases. Bias is a feature of every human decision-making process. If we design our team interactions intelligently, we can avoid the worst sort of biases.
Simon London: Here weâre talking about cognitive biases primarily, right? Itâs not that Iâm biased against you because of your accent or something. These are the cognitive biases that behavioral sciences have shown we all carry around, things like anchoring, overoptimismâthese kinds of things.
Both: Yeah.
Charles Conn: Availability bias is the one that Iâm always alert to. You think youâve seen the problem before, and therefore whatâs available is your previous conception of itâand we have to be most careful about that. In any human setting, we also have to be careful about biases that are based on hierarchies, sometimes called sunflower bias. Iâm sure, Hugo, with your teams, you make sure that the youngest team members speak first. Not the oldest team members, because itâs easy for people to look at whoâs senior and alter their own creative approaches.
Hugo Sarrazin: Itâs helpful, at that momentâif someone is asserting a point of viewâto ask the question âThis was true in what context?â Youâre trying to apply something that worked in one context to a different one. That can be deadly if the context has changed, and thatâs why organizations struggle to change. You promote all these people because they did something that worked well in the past, and then thereâs a disruption in the industry, and they keep doing what got them promoted even though the context has changed.
Simon London: Right. Right.
Hugo Sarrazin: So itâs the same thing in problem solving.
Charles Conn: And itâs why diversity in our teams is so important. Itâs one of the best things about the world that weâre in now. Weâre likely to have people from different socioeconomic, ethnic, and national backgrounds, each of whom sees problems from a slightly different perspective. It is therefore much more likely that the team will uncover a truly creative and clever approach to problem solving.
Simon London: Letâs move on to step five. Youâve done your work plan. Now youâve actually got to do the analysis. The thing that strikes me here is that the range of tools that we have at our disposal now, of course, is just huge, particularly with advances in computation, advanced analytics. Thereâs so many things that you can apply here. Just talk about the analysis stage. How do you pick the right tools?
Charles Conn: For me, the most important thing is that we start with simple heuristics and explanatory statistics before we go off and use the big-gun tools. We need to understand the shape and scope of our problem before we start applying these massive and complex analytical approaches.
Simon London: Would you agree with that?
Hugo Sarrazin: I agree. I think there are so many wonderful heuristics. You need to start there before you go deep into the modeling exercise. Thereâs an interesting dynamic thatâs happening, though. In some cases, for some types of problems, it is even better to set yourself up to maximize your learning. Your problem-solving methodology is test and learn, test and learn, test and learn, and iterate. That is a heuristic in itself, the A/B testing that is used in many parts of the world. So thatâs a problem-solving methodology. Itâs nothing different. It just uses technology and feedback loops in a fast way. The other one is exploratory data analysis. When youâre dealing with a large-scale problem, and thereâs so much data, I can get to the heuristics that Charles was talking about through very clever visualization of data.
You test with your data. You need to set up an environment to do so, but donât get caught up in neural-network modeling immediately. Youâre testing, youâre checkingââIs the data right? Is it sound? Does it make sense?ââbefore you launch too far.
Simon London: You do hear these ideasâthat if you have a big enough data set and enough algorithms, theyâre going to find things that you just wouldnât have spotted, find solutions that maybe you wouldnât have thought of. Does machine learning sort of revolutionize the problem-solving process? Or are these actually just other tools in the toolbox for structured problem solving?
Charles Conn: It can be revolutionary. There are some areas in which the pattern recognition of large data sets and good algorithms can help us see things that we otherwise couldnât see. But I do think itâs terribly important we donât think that this particular technique is a substitute for superb problem solving, starting with good problem definition. Many people use machine learning without understanding algorithms that themselves can have biases built into them. Just as 20 years ago, when we were doing statistical analysis, we knew that we needed good model definition, we still need a good understanding of our algorithms and really good problem definition before we launch off into big data sets and unknown algorithms.
Simon London: Step six. Youâve done your analysis.
Charles Conn: I take six and seven together, and this is the place where young problem solvers often make a mistake. Theyâve got their analysis, and they assume thatâs the answer, and of course it isnât the answer. The ability to synthesize the pieces that came out of the analysis and begin to weave those into a story that helps people answer the question âWhat should I do?â This is back to where we started. If we canât synthesize, and we canât tell a story, then our decision maker canât find the answer to âWhat should I do?â
Simon London: But, again, these final steps are about motivating people to action, right?
Charles Conn: Yeah.
Simon London: I am slightly torn about the nomenclature of problem solving because itâs on paper, right? Until you motivate people to action, you actually havenât solved anything.
Charles Conn: I love this question because I think decision-making theory, without a bias to action, is a waste of time. Everything in how I approach this is to help people take action that makes the world better.
Simon London: Hence, these are absolutely critical steps. If you donât do this well, youâve just got a bunch of analysis.
Charles Conn: We end up in exactly the same place where we started, which is people speaking across each other, past each other in the public square, rather than actually working together, shoulder to shoulder, to crack these important problems.
Simon London: In the real world, we have a lot of uncertaintyâarguably, increasing uncertainty. How do good problem solvers deal with that?
Hugo Sarrazin: At every step of the process. In the problem definition, when youâre defining the context, you need to understand those sources of uncertainty and whether theyâre important or not important. It becomes important in the definition of the tree.
You need to think carefully about the branches of the tree that are more certain and less certain as you define them. They donât have equal weight just because theyâve got equal space on the page. Then, when youâre prioritizing, your prioritization approach may put more emphasis on things that have low probability but huge impactâor, vice versa, may put a lot of priority on things that are very likely and, hopefully, have a reasonable impact. You can introduce that along the way. When you come back to the synthesis, you just need to be nuanced about what youâre understanding, the likelihood.
Often, people lack humility in the way they make their recommendations: âThis is the answer.â Theyâre very precise, and I think we would all be well-served to say, âThis is a likely answer under the following sets of conditionsâ and then make the level of uncertainty clearer, if that is appropriate. It doesnât mean youâre always in the gray zone; it doesnât mean you donât have a point of view. It just means that you can be explicit about the certainty of your answer when you make that recommendation.
Simon London: So it sounds like there is an underlying principle: âAcknowledge and embrace the uncertainty. Donât pretend that it isnât there. Be very clear about what the uncertainties are up front, and then build that into every step of the process.â
Hugo Sarrazin: Every step of the process.
Simon London: Yeah. We have just walked through a particular structured methodology for problem solving. But, of course, this is not the only structured methodology for problem solving. One that is also very well-known is design thinking, which comes at things very differently. So, Hugo, I know you have worked with a lot of designers. Just give us a very quick summary. Design thinkingâwhat is it, and how does it relate?
Hugo Sarrazin: It starts with an incredible amount of empathy for the user and uses that to define the problem. It does pause and go out in the wild and spend an enormous amount of time seeing how people interact with objects, seeing the experience theyâre getting, seeing the pain points or joyâand uses that to infer and define the problem.
Simon London: Problem definition, but out in the world.
Hugo Sarrazin: With an enormous amount of empathy. Thereâs a huge emphasis on empathy. Traditional, more classic problem solving is you define the problem based on an understanding of the situation. This one almost presupposes that we donât know the problem until we go see it. The second thing is you need to come up with multiple scenarios or answers or ideas or concepts, and thereâs a lot of divergent thinking initially. Thatâs slightly different, versus the prioritization, but not for long. Eventually, you need to kind of say, âOK, Iâm going to converge again.â Then you go and you bring things back to the customer and get feedback and iterate. Then you rinse and repeat, rinse and repeat. Thereâs a lot of tactile building, along the way, of prototypes and things like that. Itâs very iterative.
Simon London: So, Charles, are these complements or are these alternatives?
Charles Conn: I think theyâre entirely complementary, and I think Hugoâs description is perfect. When we do problem definition well in classic problem solving, we are demonstrating the kind of empathy, at the very beginning of our problem, that design thinking asks us to approach. When we ideateâand thatâs very similar to the disaggregation, prioritization, and work-planning stepsâwe do precisely the same thing, and often we use contrasting teams, so that we do have divergent thinking. The best teams allow divergent thinking to bump them off whatever their initial biases in problem solving are. For me, design thinking gives us a constant reminder of creativity, empathy, and the tactile nature of problem solving, but itâs absolutely complementary, not alternative.
Simon London: I think, in a world of cross-functional teams, an interesting question is do people with design-thinking backgrounds really work well together with classical problem solvers? How do you make that chemistry happen?
Hugo Sarrazin: Yeah, it is not easy when people have spent an enormous amount of time seeped in design thinking or user-centric design, whichever word you want to use. If the person whoâs applying classic problem-solving methodology is very rigid and mechanical in the way theyâre doing it, there could be an enormous amount of tension. If thereâs not clarity in the role and not clarity in the process, I think having the two together can be, sometimes, problematic.
The second thing that happens often is that the artifacts the two methodologies try to gravitate toward can be different. Classic problem solving often gravitates toward a model; design thinking migrates toward a prototype. Rather than writing a big deck with all my supporting evidence, theyâll bring an example, a thing, and that feels different. Then you spend your time differently to achieve those two end products, so thatâs another source of friction.
Now, I still think it can be an incredibly powerful thing to have the twoâif there are the right people with the right mind-set, if there is a team that is explicit about the roles, if weâre clear about the kind of outcomes we are attempting to bring forward. Thereâs an enormous amount of collaborativeness and respect.
Simon London: But they have to respect each otherâs methodology and be prepared to flex, maybe, a little bit, in how this process is going to work.
Hugo Sarrazin: Absolutely.
Simon London: The other area where, it strikes me, there could be a little bit of a different sort of friction is this whole concept of the day-one answer, which is what we were just talking about in classical problem solving. Now, you know that this is probably not going to be your final answer, but thatâs how you begin to structure the problem. Whereas I would imagine your design thinkersâno, theyâre going off to do their ethnographic research and get out into the field, potentially for a long time, before they come back with at least an initial hypothesis.
Want better strategies? Become a bulletproof problem solver
Hugo Sarrazin: That is a great callout, and thatâs another difference. Designers typically will like to soak into the situation and avoid converging too quickly. Thereâs optionality and exploring different options. Thereâs a strong belief that keeps the solution space wide enough that you can come up with more radical ideas. If thereâs a large design team or many designers on the team, and you come on Friday and say, âWhatâs our week-one answer?â theyâre going to struggle. Theyâre not going to be comfortable, naturally, to give that answer. It doesnât mean they donât have an answer; itâs just not where they are in their thinking process.
Simon London: I think we are, sadly, out of time for today. But Charles and Hugo, thank you so much.
Charles Conn: It was a pleasure to be here, Simon.
Hugo Sarrazin: It was a pleasure. Thank you.
Simon London: And thanks, as always, to you, our listeners, for tuning into this episode of the McKinsey Podcast . If you want to learn more about problem solving, you can find the book, Bulletproof Problem Solving: The One Skill That Changes Everything , online or order it through your local bookstore. To learn more about McKinsey, you can of course find us at McKinsey.com.
Charles Conn is CEO of Oxford Sciences Innovation and an alumnus of McKinsey’s Sydney office. Hugo Sarrazin is a senior partner in the Silicon Valley office, where Simon London, a member of McKinsey Publishing, is also based.
Explore a career with us
Related articles.
Strategy to beat the odds
Five routes to more innovative problem solving
Problem Solving with the Sequential Logic Structure
Sep 15, 2012
390 likes | 1.96k Views
Problem Solving with the Sequential Logic Structure. Chapter 5. Review. Recall that the: Algorithm: set of instructions telling the computer how to process a module in a solution. A flowchart: visual illustration of an algorithm. In this chapter you will learn how to:
Share Presentation
- seventh step
- sequential logic structure
- simplest logic structure
- data dictionary
Presentation Transcript
Problem Solving with the Sequential Logic Structure Chapter 5
Review ⢠Recall that the: ⢠Algorithm: set of instructions telling the computer how to process a module in a solution. ⢠A flowchart: visual illustration of an algorithm. ⢠In this chapter you will learn how to: ⢠Write an algorithm for each module in a program. ⢠Draw a flowchart to accompany in each algorithm.
Algorithm Instructions and Flowchart Symbols
Exit is used to end a subordinate module if there is no return value . ⢠Return is used when the module is to be processed within an expression . average = sum ( num1 , num2) / 2
Sequential Logic Structure ⢠The most commonly used and the simplest logic structure . ⢠all problem use the sequential structure . ⢠most problem problems use it in conjunction with one or more of the other logic structure .
Sequential Logic Structure ⢠The form of the algorithm looks like this : module name ( list of parameters) 1. instruction 2. instruction 3. âŚ.. ⌠x x.End,Exit,or Return (variable )
Flowchart Diagram for the Sequential Structure
Example: The algorithm and flowchart to enter a name and age into computer and print it on the screen. ( ) Notice that the algorithm instructions are numbered starting with the first instruction after the name of module
solution development ⢠The problem analysis chart. ⢠The interactivity chart . ⢠The IPO chart . ⢠The coupling diagram and the data dictionary . ⢠The algorithms . ⢠The flowcharts . ⢠The seventh step in solving the problem is to test the solution to catch any errors in logic or calculation .
Letâs work a problemâŚ
The Problem ⢠Marry smith is looking for the bank that will give the most return on her money over the next five years. She has $2,000 to put into a savings account. ⢠The standard equation to calculate principal plus interest at the end of a period of time is: Amount = p * (1+I/M)^(N*M) 12
The Problem ⢠Amount = p * (1+I/M)^(N*M) ⢠p= principal ( amount of money to invest) ⢠I = interest ( percentage rate the bank pays to the invested) ⢠N = number of years ( time for which the principle is invested ) ⢠M = compound interval ( the number of times per year the interest is calculated and added to the principal )
The Interactivity (Structure) Chart
Coupling Diagram
Data Dictionary ⢠in this problem all variables are local . ⢠All coupling will be done through parameters .
Algorithm and Flowchart for InterestControl Module
Algorithm and Flowchart for Read Module
Algorithm and Flowchart for Calc Module
Algorithm and Flowchart for Print Module
- More by User
Sequential Logic
Sequential Logic ENEL 111 1 7 3 Sequential Logic Circuits So far we have only considered circuits where the output is purely a function of the inputs With sequential circuits the output is a function of the values of past and present inputs This particular example is not very useful
1.37k views ⢠37 slides
SEQUENTIAL LOGIC
SEQUENTIAL LOGIC. Sequential Logic. Positive Feedback: Bi-Stability. Meta-Stability. Gain should be larger than 1 in the transition region. R. S. Q. Q. S. 0. Q. 0. Q. S. Q. 0. 0. 1. 1. Q. R. 0. 1. 0. 1. R. 1. 0. 1. 0. S. Q. Q. R. SR-Flip Flop. Q. Q. R. S. Q.
592 views ⢠29 slides
PROBLEM SOLVING WITH LOOP AND CASE LOGIC STRUCTURE
Shaykhah. PROBLEM SOLVING WITH LOOP AND CASE LOGIC STRUCTURE. Lecturer: Shaykhah. 2. Objective:Develop problems using the loop logic structure Using nested loop constructsDistinguish the different uses of three loop constructs.. Shaykhah. Pre-requisites. Lecturer: Shaykhah. 3. Short hand Assi
562 views ⢠23 slides
UNIT 3 PROBLEM SOLVING WITH LOOP AND CASE LOGIC STRUCTURE
UNIT 3 PROBLEM SOLVING WITH LOOP AND CASE LOGIC STRUCTURE. Objective: Develop problems using the loop logic structure Using nested loop constructs Distinguish the different uses of three loop constructs. Pre-requisites. Short hand Assignment Operators
912 views ⢠22 slides
Sequential Logic. Combinational logic: Compute a function all at one time Fast/expensive e.g. combinational multiplier Sequential logic: Compute a function in a series of steps Slower/more efficient e.g. shift/add multiplier Key to sequential logic: circuit has feedback
317 views ⢠15 slides
EMT1111 Logic and Problem Solving
Dr. Benito Mendoza Lecture 1. EMT1111 Logic and Problem Solving. Outline. The professor Class objectives Text book and references In class conduct Homework, assignments, and evaluation Blackboard Basic computer skills you should know Create your portfolio. The Professor.
296 views ⢠20 slides
Sequential Logic. Handouts: Lecture Slides. 6.004: Progress so farâŚ. PHYSICS: Continuous variables, Memory, Noise, f(RC) = 1 - e-t/R. COMBINATIONAL: Discrete, memoryless, noise-free, lookup table functions. What other building blocks do we need in order to compute?.
516 views ⢠41 slides
Problem Solving with the Sequential Logic Structure. Lesson 5. Overview. Algorithm Instructions Sequential Logic Structure Solution Development. Flowchart Symbols. Terminal Starts, Stops, Ends Input/Output Input data, Output information Assign Apply values to variables Process
402 views ⢠27 slides
Sequential Logic. Latches and Flip-Flops. Sequential Logic Circuits. The output of sequential logic circuits depends on the past history of the state of the outputs. Therefore, it incorporate a memory element (circuits must remember the past states of their outputs).
490 views ⢠31 slides
Sequential logic
Sequential logic. Sequential circuits simple circuits with feedback latches edge-triggered flip-flops Timing methodologies cascading flip-flops for proper operation clock skew Asynchronous inputs metastability and synchronization Basic registers shift registers. Sequential circuits.
620 views ⢠46 slides
Sequential Logic. Introduction to Computer Yung-Yu Chuang. with slides by Sedgewick & Wayne ( introcs.cs.princeton.edu ), Nisan & Schocken ( www.nand2tetris.org ) and Harris & Harris (DDCA). ALU combinational. Memory state. Review of Combinational Circuits. Combinational circuits.
678 views ⢠51 slides
Sequential Logic. By Stephen Voglewede CS 147 2/23/10. What is Sequential Logic?. Combinational Logic. Combinational Logic. The output of a combinational circuit is a function of itâs input. Consequently, it doesnât matter what the previous output was. Or what the future output will be.
329 views ⢠20 slides
Sequential Logic. Flip-Flop Circuits By Dylan Smeder. What Is A Sequential Circuit?. Circuit that has memory Sequence of inputs creates memory At the simplest a Flip-Flop circuit âSequential Circuits along with combinational circuits are the building blocks of computersâ. Simple memory.
504 views ⢠16 slides
Solving the Logic Satisfiability problem
Solving the Logic Satisfiability problem. Jesus De Loera. Overview. The Satisfiability Problem in its most general form is determining whether it is possible to satisfy a given set of logical constraints Could take many forms: Boolean expressions & logic circuits
293 views ⢠12 slides
SEQUENTIAL LOGIC. A circuitâs output depends on its previous state (condition) in addition to its current inputs The state of the circuit is kept in memory devices The state dependency is accomplished by feedback path. LATCH. Active Low. LATCH. Active High. LATCH APPLICATION.
524 views ⢠40 slides
Sequential Logic. Sequential Circuits Simple circuits with feedback Latches Edge-triggered flip-flops Timing Methodologies Cascading flip-flops for proper operation Clock skew Asynchronous Inputs Metastability and synchronization Basic Registers Shift registers. Sequential Circuits.
611 views ⢠46 slides
Sequential Logic. Lecture #7. ę°ěěě. Latch FlipFlop Active-high Clock & asynchronous Clear Active-low Clock & asynchronous Clear Active-high Clock & asynchronous Preset Active-high Clock & asynchronous Clear & Preset Shift Register Counter 4 bits Universal Counter : 74161
748 views ⢠49 slides
Sequential Logic. Lecture #7. ę°ěěě. Latch FlipFlop Shift Register Counter. SR Latch. Most simple â storage element â . Q next = (R + Q â current ) â Q â next = (S + Q current ) â. NOR. In1 In2 Out 0 0 1 0 1 0 1 0 0 1 1 0. Function Table. Storing. SR latches are sequential.
946 views ⢠64 slides
Sequential Logic. Combinatorial components: the output values are computed only from their present input values. Sequential components: their output values are computed using both the present and past input values.
366 views ⢠26 slides
Sequential Logic. ENEL 111. 1. 7. 3. Sequential Logic Circuits. So far we have only considered circuits where the output is purely a function of the inputs With sequential circuits the output is a function of the values of past and present inputs This particular example is not very useful.
466 views ⢠37 slides
Logic and Problem Solving
Logic and Problem Solving. Advanced Computer Programming. Lecture Objective. After completing this Lecture: We will be able to apply the six-step approach to problem-solving. Enabling Objectives. Identify the six steps in problem solving Describe the purpose of each step in problem solving
297 views ⢠28 slides
518 views ⢠46 slides
COMMENTS
1 introduction to problem solving and programming. Defying Logic - Business Logic Testing with Automation. Decision table. 2.3 Apply the different types of algorithm to solve problem. Categorical Propositions- Logic. Iteration. Introduction to Logic. ECDL. Instruction Set of 8086 Microprocessor.
1. Append "-". 2. Append first letter 3. Append "ay" 4. Remove first letter đ Try following those steps in different orders and see what comes out. Not the same, is it? Selection: Algorithms can use selection to determine a different set of steps to execute based on a Boolean expression.
1. Event Driven - asynchronous circuits that change state immediately when enabled. 2. Clock Driven - synchronous circuits that are synchronised to a specific clock signal. 3. Pulse Driven - which is a combination of the two that responds to triggering pulses.
Step 1: understanding the problem statement sample input/output behavior: X: 0 0 1 0 1 0 1 0 0 1 0 ... Z: 0 0 0 1 0 1 0 1 0 0 0 ... X: 1 1 0 1 1 0 1 0 0 1 0 ... Z: 0 0 0 0 0 0 0 1 0 0 0 ... Finite string pattern recognizer (step 2) Step 2: draw state diagram for the strings that must be recognized, i.e., 010 and 100 a Moore implementation
0:00 / 1:32:21 Sequential Logic Structure Problem Solving - Chap 3 Sequential Logic Structure MOHD ZAMRI OSMAN 155 subscribers Subscribe 763 views 2 years ago BCI1143 Problem...
Chapter 5 Problem Solving with the Sequential Logic Structure
A sequence is a series of actions that is completed in a specific order. Action 1 is performed, then Action 2, then Action 3, etc., until all of the actions in the sequence have been carried out. A sequence we do every day is a morning routine. You might wake up, drink some water, take a shower, eat breakfast, and so on.
Problem 2. Consider the following sequential logic circuit. It consists of three D registers, three different pieces of combinational logic (CL1, CL2, and CL3), one input IN, and one output OUT. The propagation delay, contamination delay, and setup time of the registers are all the same and are specified below each register.
Computation Structures. Menu. More Info Syllabus Calendar Instructor Insights 1 Basics of Information 1.1 Annotated Slides 1.2 Topic Videos ... 5 Sequential Logic 5.1 Annotated Slides 5.2 Topic Videos 5.3 Worksheet 6 Finite State Machines 6.1 Annotated Slides 6.2 Topic Videos 6.3 Worksheet ...
Sequential logic is used to construct finite-state machines, a basic building block in all digital circuitry. Virtually all circuits in practical digital devices are a mixture of combinational and sequential logic. A familiar example of a device with sequential logic is a television set with "channel up" and "channel down" buttons. [1]
Sequential Logic (Sequential Flow) Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly.
4. Break the problem down to its simplest parts. a. Make a simpler/smaller scale equivalent if applicable. b. Write down everything you know about every aspect of the problem 5. Draw diagrams and reframe the problem. a. Say the problem aloud b. Explain it to a friend c. Look it over slowly while reading it aloud d. Draw a picture
Sequential structure. Is the simplest and most commonly used logic structure. Used by all problems and used in conjunction with one or more other logic structures. Sequential structure used when. Programmers use sequential to tell computer to process a set of instructions in sequence from top to bottom of an algorithm.
3.2 Data Types And Data Structures In algorithmic problem solving, we deal with objects. Objects are data manipulated by the algorithm. To a cook, the objects are the various types of vegetables, meat and sauce. In algorithms, the data are numbers, words, lists, files, and so on. In solving a geometry problem, the data can be the length of a ...
By using an example, describe how the concept of algorithms can be well presented to a group of students being introduced to it. 1.1: Activity 1 - Introduction to Algorithms and Problem Solving is shared under a CC BY-SA license and was authored, remixed, and/or curated by LibreTexts. In this learning activity section, the learner will be ...
In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in range function. What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number. For example, range(1,5) gives the sequence [1, 2, 3, 4].
Chapter 5 Problem Solving With the Sequential Logic Structure - Free download as PDF File (.pdf), Text File (.txt) or read online for free. Scribd is the world's largest social reading and publishing site.
In order to solve problems with any programming language, we write code that tells the computer what operations to execute and in what order. The order must be very specific - remember the computer is not very smart - it simply follows our instructions. These operations make up what is called an algorithm.
⪠Develop problems using the loop logic structure in conjunction with the decision and sequential logic structures. ⪠Use of seven problem solving tools to solve a problem using the .
Problem Solving with Decisions COP1006. Problem Solving with the Sequential Logic Structure. Lesson 5. Overview. Algorithm Instructions Sequential Logic Structure Solution Development. Flowchart Symbols. Terminal Starts, Stops, Ends Input/Output Input data, Output information Assign Apply values to variables Process Slideshow 3973809...
In this episode of the McKinsey Podcast, Simon London speaks with Charles Conn, CEO of venture-capital firm Oxford Sciences Innovation, and McKinsey senior partner Hugo Sarrazin about the complexities of different problem-solving strategies.. Podcast transcript. Simon London: Hello, and welcome to this episode of the McKinsey Podcast, with me, Simon London.
1. Define the problem. Diagnose the situation so that your focus is on the problem, not just its symptoms. Helpful problem-solving techniques include using flowcharts to identify the expected steps of a process and cause-and-effect diagrams to define and analyze root causes.. The sections below help explain key problem-solving steps.
Sequential Logic Structure ⢠The most commonly used and the simplest logic structure . ⢠all problem use the sequential structure . ⢠most problem problems use it in conjunction with one or more of the other logic structure .
61 likes, 2 comments - charan_techstudio on February 20, 2024: "5 Stepsââ 1. Start with the Basics: - Ensure you have a solid understanding of the basics ..."