Computer Fundamentals and Introduction to Programming · Lecture Notes
Chapter 1.5: Computation and Computational Thinking
A computer is often pictured as a fast calculator. Yet a search engine’s result list, the route a map suggests, and a phone’s face recognition are computation too: in each of them, data is processed according to definite rules. These notes first explain this broad notion of computation and what computer science is about. They then cover the short history of computation, the move from fixed-program machines to stored-program computers, and the theoretical foundation of that move, the Turing machine; a Turing machine adding 1 to a binary number is traced step by step. The two kinds of knowledge, “what is” and “how to”, are compared through square-root finding and Euclid’s algorithm. The last part shows four thinking tools that bring a large problem into a form a computer can solve, namely decomposition, pattern recognition, abstraction, and algorithm design, with examples.
Learning outcomes
- Computation
- Explain computation as the processing of data according to rules; give examples of computation beyond arithmetic; identify the input, the process, the output, and the resources of a task.
- Models of computation
- Distinguish fixed-program from stored-program machines; trace the operation of a Turing machine step by step in terms of tape, head, state, and transition rules; list the limits of computers.
- Knowledge and algorithms
- Distinguish declarative from imperative knowledge; trace the square-root method and Euclid’s algorithm with a trace table; justify why an algorithm stops.
- Computational thinking
- Apply decomposition, pattern recognition, abstraction, and algorithm design to a real problem; choose test cases made up of normal, boundary, and invalid inputs for an algorithm.
1.5.1Computation
To most people the word “computation” recalls the four operations from school: addition, subtraction, multiplication, and division. In computer science the notion is much broader. Looking up a word in a dictionary, sorting a class list by surname, and deciding when a traffic light turns green are all computation. This part introduces the common structure of computation and the parts that make it possible.
1.5.1.1What is computation?
Finding the average of a student’s four exam grades is one of the simplest examples of computation. We have the grades: 70, 85, 60, and 75. These numbers are the material to be processed. The rules to apply to it are clear as well: first the grades are added, then the total is divided by 4. Applying the rules gives a result: 72.5. Every example of computation has these three parts: the data to be processed, the rules to apply, and the result produced.
Computation is the transformation of data into a result by processing it according to definite rules. The data to be processed is called the input, the step-by-step application of the rules is called the process, and the result produced is called the output.
Two words in the definition are especially important. The first is “rules.” Computation is not done on a whim: when the same rules are applied to the same input, the same output comes out every time. Whoever computes the average today, or tomorrow, finds 72.5. The second is “processing.” Merely storing or displaying data is not computation; the data must be transformed according to a rule.
Figure 1.5.1 shows this structure. The resources in the dashed box are easy to overlook at first glance, but every computation depends on them. A process takes time: adding four numbers takes a moment, while sorting millions of records can take minutes. A process needs memory: the grades and the running total must be kept somewhere. Every step spends energy: the phone’s battery and the data center’s electricity bill are both consequences of this. If the data comes from somewhere else or goes somewhere else, communication is needed: the grades are read over the network from the student information system. Resources are not unlimited, so a method that does the same job with less time, memory, and energy is more valuable.
How is the average of the grades 70, 85, 60, and 75 computed? Which intermediate result is kept at each step?
| Step | Operation | Running total |
|---|---|---|
| 1 | The running total starts at 0 | 0 |
| 2 | 0 + 70 | 70 |
| 3 | 70 + 85 | 155 |
| 4 | 155 + 60 | 215 |
| 5 | 215 + 75 | 290 |
| 6 | 290 ÷ 4 | 72.5 |
Result: the average is 72.5. Addition was performed four times and division once. Memory holds only the total so far and the number of grades read. Even if the number of grades grew to 40, only these two values would be kept; what changes is the number of additions.
The last observation in the example is important. As the number of grades grows, the number of additions grows too; 40 grades need 40 additions. How the running time of a task grows with the size of its input is one of the criteria that decide whether a method is good.
1.5.1.2Computation is not only arithmetic
Finding an average is a task done with numbers. Most of what computers do day to day, however, does not look directly related to numbers. An email program orders incoming messages by date and moves unwanted ones to a separate folder. A map application finds the shortest route between two points. A translation program renders a sentence in one language into another. All of these are processing of data according to rules, and therefore all of them are computation.
| Kind | Input | Rule | Output |
|---|---|---|---|
| Search | A dictionary and the word “tape” | Find the word using alphabetical order | The meaning of the word |
| Sorting | Class list | Arrange the surnames in alphabetical order | Sorted list |
| Decision making | Exam grade 47 | If the grade is below 50, “failed”; otherwise “passed” | “failed” |
| Transformation | Photograph | Turn the color of every pixel into gray | Black-and-white photograph |
| Communication | A message | Split the message into packets, address them, send them | Message that reaches the recipient |
Table 1.5.1 puts five different kinds of computation side by side. In none of them are the four operations in the foreground, yet all of them have the same three parts. In a search, the input is a dictionary and the word sought; the rule is to use alphabetical order to go to the right page. In decision making the rule is a comparison: since 47 < 50 is true, the output is “failed.” In a transformation, every pixel of a photograph is changed by the same rule. Even communication has rules: a message is split into pieces of a certain size and an address is written at the head of each piece.
This breadth also explains why computers are used in so many fields. At its core a computer is a machine that processes data according to rules. If a task can be described with explicit rules and its data can be turned into numbers, the task can be given to a computer. Text, images, and sound are already stored in a computer as sequences of numbers, so operations on them are computation as well.
A campus canteen deducts the lunch fee from the balance on a student card when the card is tapped. The fee is 45 TL and the balance on the card is 120 TL. Which kinds of computation are involved?
- Communication. The card reader sends the card number to the canteen’s server.
- Search. The server looks the card number up among the records and finds the balance: 120 TL.
- Decision making. Since 120 ≥ 45 is true, the payment is accepted. If the balance were below 45 TL, the payment would be rejected.
- Arithmetic. The new balance is computed: 120 − 45 = 75 TL.
- Communication. The result is sent back to the reader and the screen shows “Remaining: 75 TL.”
In a single card tap, four different kinds of computation run one after another. Arithmetic is only one of them.
Thinking that only electronic computers carry out computation. Computation is a process, not a machine. A teacher sorting a class list with pen and paper, and a driver comparing routes and choosing the shortest, are computing too. A computer is a tool that carries out the same process much faster and without mistakes.
1.5.1.3The building blocks of computation
For a computation to be designed on paper and run on a machine, several different parts have to come together. These parts can be grouped under six headings.
- Mathematics
- Makes it possible to operate on quantities and relations. Operations such as addition, division, and comparison are the tools of mathematics.
- Logic
- Decides whether a condition is true or false. The answer to “Is the grade below 50?” is a logical value: true or false.
- Data
- The inputs that represent the problem and the intermediate results produced during the computation. In the average example, the grades and the running total are data.
- Algorithm
- A finite, orderly sequence of operations. “Set the total to 0, add each grade, divide by the number of grades at the end” is an algorithm.
- Hardware
- The system that physically carries out the steps: processor, memory, wires. However good an algorithm is, no result is obtained without a machine to run it.
- Programming language
- The means of writing the algorithm in a form the computer can understand. The same algorithm can be written in Java, Python, or C.
These parts do not replace one another; they complement one another. Mathematics and logic determine which operations can be performed, data determines what is processed, and the algorithm determines the order of operations. The programming language puts the algorithm into a form the machine understands, and the hardware runs it. A recipe analogy makes the relationship concrete: the ingredients are data, the recipe is the algorithm, the language the recipe is written in is the programming language, and the stove and pot are the hardware. Measurements and checks such as “Is it thick enough yet?” are the share of mathematics and logic.
| Building block | Counterpart in the average computation |
|---|---|
| Mathematics | Addition and division: (70 + 85 + 60 + 75) ÷ 4 |
| Logic | The question “Is there a grade left to read?”; when the answer is false, the addition ends |
| Data | The four grades, the running total, and the number of grades |
| Algorithm | Set the total to 0; add each grade to the total; divide the total by the number of grades; write the result |
| Hardware | The processor that keeps the total in memory and does the addition |
| Programming language | The algorithm written in a language such as Java |
Thinking that an algorithm and a program are the same thing. An algorithm is the idea that describes the steps by which a task is done; it can be written in English sentences or as a flowchart. A program is the counterpart of that idea in a particular programming language. One algorithm can have many different programs. If the algorithm is wrong, the program gives wrong results whatever language it is written in.
1.5.2Computer science
Knowing how to use a computer and knowing computer science are different things. A person who prepares a document in a word processor is using a computer. Computer science asks questions such as how that word processor stores the text, by what method the spell checker works, and why the program slows down as the document grows. This part introduces the core areas of interest of computer science and the responsibilities of the field toward society.
1.5.2.1What does computer science study?
Computer science is the discipline that studies how information is represented, how it is processed, and by what methods problems can be solved. It concerns not only using tools but also the methods behind the tools and the limits of those methods.
The broad field of computer science can be grouped under four main areas of interest.
Abstraction. Hiding unnecessary details and focusing on the essential structure. A user who saves a file does not know which magnetic region of the disk or which memory cell the data is written to; they see only the “Save” button. The details of the disk are hidden behind a layer of abstraction. Computer systems consist of many such layers stacked on top of one another. Abstraction is also one of the components of computational thinking.
Algorithms. Designing solution steps and analyzing them. Analysis asks whether an algorithm gives the correct result and how much time and memory it uses. Of two algorithms that solve the same problem, one may finish in a second and the other in an hour.
Systems. Understanding how hardware and software work together. Operating systems, networks, databases, and compilers are topics under this heading. Why a program runs slowly often depends not on the algorithm but on some part of the system, for example waiting for data to arrive over the network.
People and society. Evaluating the effects of technology on people, its security, and its ethics. A piece of software can work flawlessly from a technical point of view and still harm people.
1.5.2.2Technology and responsibility
Computers are now used in decisions that directly affect human lives, from banking to health, from education to hiring. A piece of software therefore has to do more than work correctly: it must also be fair, secure, and usable by everyone. Four areas of responsibility stand out.
- Accessibility
- Equal access to technology for different users. A visually impaired user must be able to listen to a web page with a screen reader. For this, every image on the page needs a text description. A color-blind user cannot read a chart separated only by red and green; the information must be given by shape or text in addition to color.
- Privacy
- Using personal data only for its stated purpose and securely. A shopping app asks for an address for delivery; selling the same address to advertisers without the user’s knowledge goes beyond that purpose. In Turkey, Law No. 6698 on the Protection of Personal Data sets rules on this subject.
- Fairness
- Data and algorithms must not produce discriminatory results. If an algorithm learns from past data, it can learn past biases as well. Even if the algorithm itself looks neutral, its results can work against particular groups.
- Sustainability
- Taking energy consumption, hardware lifetime, and electronic waste into account. Data centers use large amounts of electricity. Devices that become obsolete quickly turn into electronic waste, and this waste contains metals that harm nature.
A bank uses software that evaluates loan applications. The software gives a score by looking at the applicant’s income, debt history, and neighborhood. During an audit it is noticed that applications from certain neighborhoods receive lower scores even when income and debt history are similar. Which area of responsibility does this concern, and what can be done?
- Identify the area. People in similar situations get different results only because of where they live. This is a discriminatory outcome; the subject is fairness.
- Look for the cause. The neighborhood may be correlated with income level or other social characteristics. The algorithm may be drawing an indirect distinction by using the neighborhood.
- Remedy. The neighborhood information can be removed from the scoring. Results are compared across groups at regular intervals. A person whose application is rejected is given a way to learn the reason and to appeal.
The same system also processes the applicants’ identity and income information. Using this information only for the loan evaluation and storing it securely is a privacy responsibility. A single piece of software can involve more than one area of responsibility at the same time.
Thinking “if a computer decided, it is impartial.” An algorithm is influenced by the data it is given and by the choices of those who design it. If the data it was trained on is biased, its results are biased too. Impartiality does not come by itself; it must be measured and audited.
1.5.3The history of computation
Today’s computers are the product of ideas accumulated over several generations. Many of these ideas were conceived long before the technology to implement them appeared. This part describes the main milestones in the history of computation and, perhaps the most important of them, the idea of the stored program.
1.5.3.1Milestones
Figure 1.5.2 shows the five eras on a timeline. Each era takes the ideas of the one before and implements them with faster, smaller, and cheaper technology.
The 1800s: mechanical designs. The English mathematician Charles Babbage designed a mechanical computing machine in the 1830s, which he called the Analytical Engine. The machine was to run on gears. It would have a separate computing unit and a memory unit that held numbers. It would also read its instructions from punched cards. The idea of punched cards came from the Jacquard loom, whose patterns were determined by holes in cards. Babbage’s machine could not be completed with the craftsmanship available at the time. Even so, its design for the first time combined the basic parts of today’s computers. In her 1843 notes on the machine, the mathematician Ada Lovelace gave a step-by-step method for computing Bernoulli numbers. This method is regarded as one of the first algorithms written to be run on a machine. Lovelace foresaw that the machine could operate not only on numbers but on anything that can be expressed with symbols, for example musical notes.
The 1930s: theoretical foundation. In a paper published in 1936, Alan Turing defined an abstract model of computation. Known today as the Turing machine, this model gave a mathematical answer to the question “what exactly is a computation?” The same paper also showed that some problems cannot be solved by any machine. In these years the first experimental machines that computed with electronic circuits also began to be built.
The 1940s: electronic machines. During the Second World War, the Colossus machines were built in Britain to break encrypted messages. In the United States, ENIAC was developed to compute firing tables for artillery shells. These machines ran on thousands of vacuum tubes and filled a whole room. They were thousands of times faster than mechanical machines. However, to move on to a new job, the wires and switches had to be rearranged by hand.
The 1950s: the stored program and the first high-level languages. Computers that also kept their instructions in memory became widespread. Programmers were now dealing not with the machine’s wires but with instructions in memory. Fortran, developed by IBM in 1957, made it possible to write scientific calculations in a language resembling mathematical formulas. Fortran became the first widely used high-level programming language.
Today: computation everywhere. Thanks to the transistor, the integrated circuit, and the microprocessor, computers have shrunk to fit in a pocket. Today phones, cloud services, artificial intelligence applications, and distributed systems made up of thousands of connected machines all run on the same basic ideas.
The lesson of this short history is this: as hardware became faster and smaller, basic ideas such as the algorithm and the stored program became applicable in wider fields. The ideas did not change; the technology carrying them did. Babbage’s gears, ENIAC’s vacuum tubes, and today’s transistors do the same job: they process data according to rules.
| Era | Technology | How is the program supplied? |
|---|---|---|
| 1800s | Gears, levers | Punched cards (design) |
| 1930s | Abstract model on paper | Table of transition rules |
| 1940s | Vacuum tubes | Wiring and switch layout |
| 1950s | Vacuum tubes, then transistors | Instructions stored in memory; Fortran |
| Today | Chips with billions of transistors | Programs written in high-level languages |
Thinking that one person invented the computer at a single moment. The computer developed over more than a hundred years with the contributions of many people in different countries. Babbage put forward the design, Lovelace the idea of the algorithm, Turing the theoretical model, and the engineers of the war years the electronic machines. Each built on the one before.
1.5.3.2Fixed program and stored program
The great majority of early machines were built to do a single job. A desk calculator performs only the four operations. The rotary knob of an old washing machine selects one of a few fixed programs determined by gears. In these machines the “program” is the physical structure of the machine itself. To make the machine do a new job, it has to be rebuilt.
In a fixed-program machine, the task to be done is determined by the physical layout of the machine or by a special mechanism. In a stored-program machine, the instructions are kept in memory, just like the data to be processed. The machine reads the instructions from memory one by one and carries them out.
Figure 1.5.3 puts the two approaches side by side. The memory on the right has five cells. The top three hold instructions and the bottom two hold data. As far as memory is concerned, there is no difference between these cells; they are all bit sequences. What makes the content of a cell an instruction is that the processor reads it as an instruction. The central processing unit (CPU) fetches an instruction from memory, decodes and executes it, then moves on to the next instruction. The instruction reads the data it needs from the same memory.
The consequence of this simple idea is large. To make the machine do a new job, there is no need to touch the wires; loading new instructions into memory is enough. The same computer becomes a word processor in the morning, a game in the afternoon, and a video player in the evening. Physically nothing changes; only the instructions in memory change. On ENIAC, switching to a new job could take days because the wires had to be reconnected. On a stored-program machine, the same switch takes only as long as loading a new program into memory.
The stored-program idea spread to a wide audience through the report John von Neumann wrote in 1945 for a machine called EDVAC. This structure, in which instructions and data sit in the same memory, is today called the von Neumann architecture. The first electronic computer to run a program stored in memory was a small experimental machine that ran at the University of Manchester in England in 1948. Almost all of today’s computers are a variant of this architecture.
| Approach | How is the program determined? | Flexibility |
|---|---|---|
| Fixed program | The physical layout or a special mechanism of the machine | A specific task |
| Stored program | Instructions are stored in memory like data | Different tasks by changing the program |
| General purpose | An architecture that can run very different programs | A wide range of applications |
Table 1.5.4 also contains a third row: the general-purpose computer. The stored-program idea is a precondition for the general-purpose computer. A machine whose instructions can be changed can carry out almost any computation with suitable instructions. Personal computers and smartphones are general purpose. The opposite is special-purpose devices designed for a single job.
Does each of the following three devices work with a fixed program or a stored program? A mechanical wristwatch, a game console, and a digital camera.
- Mechanical wristwatch. What the watch does is determined by the ratios of its gears. To make the watch do a new job, the gears must be changed. It is fixed-program.
- Game console. Each new game is a new program loaded into memory. The same hardware runs thousands of different games and gains new features through updates. It is stored-program.
- Digital camera. To the user it seems to do a single job: taking photographs. Inside, however, there is a processor running software stored in memory. The manufacturer can add new shooting modes to the camera with a software update. Seen from inside it is stored-program; but because the user cannot load their own programs, it is not general purpose.
The third device shows that the two distinctions are independent of each other. A device can work with a stored program and still be designed for a single job. So are the small computers inside today’s washing machines, ovens, and cars.
Thinking that a stored-program machine is a “faster” machine or one with “more memory.” The distinguishing feature is not speed but where the instructions are kept. If the instructions are stored in memory like data and can be changed, the machine is stored-program. A very fast machine can be fixed-program, and a slow machine can be stored-program.
1.5.4Models of computation
To ask what a computer can and cannot compute, we first need a precise definition of “computation.” Real computers are too complicated for this: processor types, memory sizes, and programming languages differ greatly. Computer science therefore uses simple machine models stripped of details. The most famous of these models is the Turing machine. This part introduces the parts of a Turing machine, runs a machine step by step, and explains what this model says about the limits of computers.
1.5.4.1The Turing machine
Turing built his model by observing a person doing a calculation with pen and paper. The person writes symbols on the paper, reads what has been written, and decides what to do in the next step by looking at the information held in mind at that moment and the symbol being seen. Turing broke this behavior down into its simplest parts.
A Turing machine is an abstract machine model used to explain algorithmic computation. It consists of four parts:
- Tape: a strip divided into cells that can extend as far as needed in both directions. Each cell holds a symbol. A blank cell is shown as □.
- Read/write head: at any moment it is over a single cell. It reads the symbol in that cell, may write a new symbol in its place, and then moves one cell right or left, or stays where it is.
- State: the information the machine is “holding in mind” at that moment. States are written with names such as q0 and q1. When the machine reaches the special state HALT, it finishes running.
- Transition rules: a table that says what to do for each (state, symbol read) pair. A rule specifies three things: the symbol to write, the movement of the head, and the new state.
Figure 1.5.4 is a snapshot of the machine. The binary number 1011 is written on the tape; the remaining cells are blank. The triangle under the head marks the cell to be read. The box under the head shows the machine’s state: q0.
The power of the model comes from its simplicity. A step of the machine always has the same form:
- The symbol under the head is read.
- In the transition-rule table, the row matching the (current state, symbol read) pair is found.
- The symbol the row specifies is written into the cell.
- The head moves one cell in the direction the row specifies, or stays in place.
- The machine goes to the new state the row specifies. If the new state is HALT, the machine stops; otherwise it returns to the first step.
The machine’s “intelligence” is only in the rule table. The machine looks at the table and does what it says; it does not remember past steps and does not plan ahead. If there is something it needs to remember, it carries it either as a symbol on the tape or in its state. The tape of unbounded length is the machine’s memory. Real computers have finite memory; the model sets the memory problem aside and focuses only on the question “can this job be done with rules?”
Thinking that a Turing machine is a device that was actually built. A Turing machine is a model defined on paper; its purpose is not to build a computer but to define precisely what computation is. Enthusiasts have since built small demonstration machines, but the value of the model is theoretical.
1.5.4.2Transition rules
Only the rule table determines what a Turing machine does. The first example is a machine that adds 1 to a binary number written on the tape. Adding 1 in binary is similar to adding 1 in decimal. We start at the rightmost digit. If the digit is 0, it becomes 1 and the job is done. If the digit is 1, it becomes 0 and a carry is passed to the digit on its left; the same operation is repeated there. If no digit is left to the left of the number, a 1 is written there.
| Rule | State | Read | Write | Move | New state | Meaning |
|---|---|---|---|---|---|---|
| 1 | q0 | 1 | 0 | left | q0 | 1 + 1 = 10: the digit becomes 0, the carry moves left |
| 2 | q0 | 0 | 1 | halt | HALT | 0 + 1 = 1: the carry ends at this digit |
| 3 | q0 | □ | 1 | halt | HALT | Left of the number is blank: the carry becomes a new digit |
Table 1.5.5 consists of three rules. The machine has a single working state, q0. Three symbols can be read in this state: 1, 0, and □. For each of them there is exactly one rule in the table. The machine is therefore never undecided about what to do at any step. Rule 1 does the carrying and leaves the machine in q0, so the same rule can be applied to all consecutive 1s. Rules 2 and 3 stop the machine.
This table fits the knowledge of binary addition into just three rows. The machine does not know the notions of “binary number” or “carry”; it only reads and writes symbols. It is the human who designed the table who gives the rules their meaning.
1.5.4.3Step by step: 111 + 1
Let us run the machine with 111 written on the tape. In decimal, 111₂ is 4 + 2 + 1 = 7; the expected result is 8, that is, 1000₂. The head is over the rightmost digit and the state is q0.
From the starting situation in Figure 1.5.5, the machine follows these steps:
- Step 1. The symbol read is 1, the state is q0. The matching rule is rule 1: 0 is written, the head moves left, and the state stays q0. The tape becomes □□110□. At the rightmost digit, 1 + 1 = 10 has been computed: 0 was written in the digit and the carry 1 was moved one cell to the left.
- Step 2. The head is at cell 4 and the symbol read is again 1. Rule 1 is applied again. The tape becomes □□100□; the carry is still going.
- Step 3. The head is at cell 3 and the symbol read is 1. Rule 1 is applied a third time. The tape becomes □□000□. All the digits of the number have turned to 0, but the carry has not been written yet.
- Step 4. The head is at cell 2 and the symbol read is □. The matching rule is rule 3: 1 is written and the machine goes to the state HALT. The tape becomes □1000□.
Figure 1.5.6 shows the last two steps. The whole run is summarized in the trace table below. Each row of the table shows the situation before a rule is applied and the tape after it is applied.
| Step | Head | State | Read | Rule | Tape after | Head after | State after |
|---|---|---|---|---|---|---|---|
| 1 | 5 | q0 | 1 | 1 | □□110□ | 4 | q0 |
| 2 | 4 | q0 | 1 | 1 | □□100□ | 3 | q0 |
| 3 | 3 | q0 | 1 | 1 | □□000□ | 2 | q0 |
| 4 | 2 | q0 | □ | 3 | □1000□ | 2 | HALT |
The machine halted in four steps and 1000 was left on the tape: 1000₂ = 8 = 7 + 1. The result is correct. Table 1.5.6 also contains an important observation: in every row, only the “State” and “Read” columns determined what was to be done. The machine’s earlier steps, the rest of the tape, and how many digits the number had did not influence any decision.
The number of steps also depends on the input. The machine spends one step for each run of consecutive 1s from the right, and one more step where the carry ends. For a number with k consecutive 1s at its right end, the machine halts in k + 1 steps. 111 has three consecutive 1s at its right end; the number of steps is 3 + 1 = 4.
The same machine is run with 10011 (binary 19) on the tape; the head is at the rightmost digit. In how many steps does the machine halt, and what is left on the tape?
| Step | Read | Rule | Action | Tape after |
|---|---|---|---|---|
| 1 | 1 | 1 | write 0, move left | 10010 |
| 2 | 1 | 1 | write 0, move left | 10000 |
| 3 | 0 | 2 | write 1, HALT | 10100 |
The machine halts in three steps. 10100 is left on the tape: 16 + 4 = 20 = 19 + 1. Since there are two 1s at the right, the number of steps is 2 + 1 = 3. The digits to the left of the 0 where the carry ended (the leftmost 1 and the 0) were never touched. Rule 3 was not used at all on this input, because the carry ended before the head reached a blank cell.
Thinking that the machine stops after applying rule 1. The new state of rule 1 is q0, not HALT; the machine keeps running. The machine stops only when a rule whose new state is HALT is applied. In this machine those are rules 2 and 3.
1.5.4.4Memory in the state: a parity check
The machine that adds 1 had a single working state. For some tasks the machine must keep in mind some information about the symbols it has read. This information is stored in the state. A machine that finds out whether the number of 1s in a bit string is even or odd shows this clearly. This machine, one of the ready-made machines in the Turing Machine simulator, has two working states: “even” and “odd.” The head starts at the leftmost symbol of the string and moves right.
| Rule | State | Read | Write | Move | New state | Meaning |
|---|---|---|---|---|---|---|
| 1 | even | 0 | 0 | right | even | 0 does not change the number of 1s |
| 2 | even | 1 | 1 | right | odd | One more 1: the number became odd |
| 3 | odd | 0 | 0 | right | odd | 0 does not change the number of 1s |
| 4 | odd | 1 | 1 | right | even | One more 1: the number became even |
| 5 | even | □ | E | halt | HALT | End of the string; the number of 1s is even |
| 6 | odd | □ | O | halt | HALT | End of the string; the number of 1s is odd |
The machine in Table 1.5.7 moves along the tape without changing anything; it writes back into each cell the symbol it read. The only thing that changes is the state. When the machine reads a 1, the state flips from even to odd or from odd to even; when it reads a 0, the state stays the same. When the blank cell at the end of the string is reached, the state says whether the number of 1s read so far is even or odd. The machine writes this answer into the blank cell as E or O and halts.
The parity machine is run with 1101 on the tape. How does the state change at each step, and what is written on the tape?
| Step | Head | State | Read | Rule | New state |
|---|---|---|---|---|---|
| 1 | 1 | even | 1 | 2 | odd |
| 2 | 2 | odd | 1 | 4 | even |
| 3 | 3 | even | 0 | 1 | even |
| 4 | 4 | even | 1 | 2 | odd |
| 5 | 5 | odd | □ | 6 | HALT (O written) |
The machine halts in five steps and the tape becomes 1101O. The string has three 1s; three is odd. Without doing any counting, only by moving back and forth between two states, the machine reached the right answer. The number of steps is one more than the length of the string: four symbols and one blank cell.
This machine shows that the state of a Turing machine is a kind of small memory. The machine does not know the exact number of 1s; it knows only as much as the task requires, namely whether the number is even or odd. The same idea is used in real computers: the parity bit sent to detect whether data was corrupted in transmission is found with exactly this computation.
1.5.4.5The universal Turing machine
Every Turing machine seen so far did a single job: one added 1 to a number, the other checked parity. A new job needed a new rule table, that is, a new machine. In this respect every Turing machine resembles a fixed-program machine. In the same paper, Turing also defined a machine that goes beyond this limit.
A universal Turing machine is a Turing machine that, when it starts running, has two things written on its tape: the rule table of another Turing machine and the input of that machine. The universal machine reads this table and applies it step by step, doing exactly the job that machine would do; that is, it imitates it.
The universal machine’s own rule table is fixed and never changes. What changes is the table written on its tape. If the table of the machine that adds 1 is written, it adds 1; if the table of the parity machine is written, it checks parity. The rule table is no longer part of the machine but data sitting on the tape.
This idea is the theoretical foundation of the stored-program idea defined in Definition 1.5.3. The tape of the universal Turing machine corresponds to the computer’s memory, the rule table on the tape to the program in memory, and the fixed rules of the universal machine to the processor’s circuits that decode and carry out instructions. Turing put this idea forward on paper in 1936. Real stored-program computers could be built only more than ten years later.
| Universal Turing machine | Stored-program computer |
|---|---|
| Tape | Memory |
| Rule table written on the tape | Program in memory |
| Input written on the tape | Data in memory |
| Fixed rules of the universal machine | The processor circuits that fetch and carry out instructions |
Although the Turing machine looks simple, it is very powerful. Given enough time and memory, a Turing machine can carry out every computation that any computer known today can. In other words, no computer today can perform a computation that a Turing machine cannot. Computers are much faster than Turing machines, but the set of things they can compute is the same. The Turing machine is therefore an adequate model for studying the question “what can a computer compute?”
Thinking that the universal Turing machine is the one with the infinite tape or the two-way head. The infinite tape and a head that can move in both directions are in every Turing machine. What sets the universal machine apart is that it takes the description of another machine as input and can imitate it.
1.5.4.6The limits of computers
Computers are very fast, but they cannot do everything. Some limits come from resources, some from the nature of data and models, and some from computation itself. Six limits stand out.
- Time
- Large inputs can make some algorithms impractical. If an algorithm’s running time grows very quickly as the input grows, the result does not arrive within a time the user can wait.
- Memory
- Data and intermediate results are kept in a finite storage area. The tape of a Turing machine is infinite; the memory of a real computer is not.
- Energy
- Every operation and every data transfer consumes energy. A phone’s battery and a data center’s cooling system and electricity bill are the everyday faces of this limit.
- Computability
- For some problems there is no algorithm that gives the correct result on every input. The best-known example is the halting problem.
- Data quality
- Missing or faulty input leads even a correct algorithm to a wrong result.
- Model limits
- A program represents only selected features of the real world. A feature that is not in the model is not taken into account in the result either.
The first three limits are resource limits. A faster processor, a larger memory, or a more efficient algorithm pushes these limits back. Computability is a different kind of limit: it cannot be overcome however powerful hardware becomes. The last two limits arise from the connection of computation to the real world.
A program tries to break a password by trying all possible keys one by one, and it can try 109 (one billion) keys per second. If the key is 40 bits long, how long does it take in the worst case? What happens if the key is 64 bits?
- Number of possible keys. With n bits, 2n different keys can be written. For 40 bits there are 240 = 1,099,511,627,776, about 1.1 × 1012 keys.
- Time for 40 bits. 240 ÷ 109 ≈ 1,099.5 seconds, about 18 minutes.
- Time for 64 bits. There are 264 ≈ 1.84 × 1019 keys. 1.84 × 1019 ÷ 109 ≈ 1.84 × 1010 seconds. Since a year is about 3.16 × 107 seconds, the time is about 584 years.
- Effect of hardware. A computer twice as fast halves the time, to about 292 years. Adding just one bit to the key doubles the time again.
When the key length grows from 40 bits to 64 bits, an increase of only 24 bits, the time grows by a factor of 224 ≈ 16.8 million. Algorithms whose running time doubles with every bit of input in this way become impractical on large inputs. Encryption systems rely on exactly this time limit.
The halting problem. The best-known example of the computability limit is the halting problem. The question is this: given any program and its input, can a general algorithm be written that correctly decides in every case whether the program will ever stop? For some programs the answer is easy. It is clear that the Turing machine that adds 1 halts on every input. For others, finding the answer is very hard. The short program below is a famous example:
n = 6
while n ≠ 1
if n mod 2 = 0
n = n / 2
else
n = 3 * n + 1
print("stopped")If the program is run with n = 6, n takes the values 6, 3, 10, 5, 16, 8, 4, 2, 1 in turn and the program stops after eight iterations. If it is run with n = 27, it takes 111 iterations and the intermediate values rise as high as 9,232. Whether this program stops for every positive n is still unknown today. It has been tried with computers up to very large numbers and has always been seen to stop, but it has not been proved that it stops for every n.
In 1936 Turing showed something stronger: a general algorithm that correctly decides, for every program and every input, whether it will stop can never be written. The main idea of the argument is as follows. Suppose such an “oracle” algorithm exists. Using this oracle, a program that behaves contrarily can be written: the program asks the oracle about itself; if the oracle says “it halts,” the program loops forever, and if the oracle says “it does not halt,” the program halts at once. When this contrary program is run on itself, the oracle is wrong whatever it answers. So such an oracle cannot exist. This result has nothing to do with speed or memory; it is a logical impossibility.
A weather station sends four temperature readings within an hour: 21.4 °C, 22.1 °C, 23 °C, and −99 °C. When the sensor cannot take a reading, it sends the value −99. What is the result if the program that computes the average uses all four values?
- Sum. 21.4 + 22.1 + 23 + (−99) = −32.5.
- Average. −32.5 ÷ 4 = −8.125 °C.
- Correct computation. −99 is not a measurement but a marker meaning “no reading”; it must be removed from the computation. The average of the remaining three values is (21.4 + 22.1 + 23) ÷ 3 = 66.5 ÷ 3 ≈ 22.17 °C.
The averaging algorithm worked flawlessly; the error was in the data. This situation is called “garbage in, garbage out.” The data-quality limit can be overcome only by checking the data beforehand.
Model limits. A navigation application models roads by their lengths and average speeds. If the model does not know that a road was closed that morning because of flooding, the application keeps recommending the closed road. The program did not compute wrongly; it could not know a feature of the real world that is missing from the model. Every program works with a model, and everything outside the model is outside the program as well.
Thinking that every limit can be overcome with more powerful hardware. The limits of time, memory, and energy can be eased with better hardware or a better algorithm. Computability limits such as the halting problem, however, are theoretical: such an algorithm does not exist at all, so no hardware can run it.
1.5.5Knowledge and algorithms
There are two different ways of knowing something. A person can know a fact: “Ankara is the capital of Turkey.” A person can also know how something is done: “To go to Ankara, take this bus and get off at this stop.” Computer science is mainly concerned with the second kind, because to make a computer do a job, you have to describe how the job is done, step by step. This part compares the two kinds of knowledge, defines the algorithm, and traces two classic algorithms in detail: square-root finding and Euclid’s algorithm.
1.5.5.1Declarative and imperative knowledge
Declarative knowledge explains what is true or what a concept is. Imperative knowledge explains, in steps, how to reach a result.
Figure 1.5.7 puts the two kinds side by side. The sentence “the interior angles of a triangle add up to 180°” gives a true piece of information but does not tell us how to do a job. With this knowledge the missing angle of a triangle can be found; but even for that a method is still needed. The steps on the right, by contrast, can be applied directly. A person or machine that follows the steps reaches the result even without fully understanding what a square root is.
The definition of the square root is also declarative knowledge: “the square root of x is the positive number whose square is x.” This definition is useful for checking whether a number is a square root. Since the square of 5 is 25, 5 is the square root of 25. But the definition does not show how to find the square root of 10. Declarative knowledge answers the question “what,” imperative knowledge the question “how.”
| Topic | Declarative knowledge (what?) | Imperative knowledge (how?) |
|---|---|---|
| Square root | √x is the positive number whose square is x. | Start with a guess, update the guess with the averaging formula, stop when it is close enough. |
| Prime number | A prime number is an integer greater than 1 that is divisible only by 1 and itself. | Divide the number by every number from 2 up to its square root; if none divides it evenly, the number is prime. |
| Sorted list | Each element is not greater than the one after it. | Find the smallest element and put it first; repeat the same step with the remaining elements. |
| Directions | The library is north of the main building. | Enter through the main gate, turn right, and walk to the second building. |
Table 1.5.9 shows the two faces of the same topic in each row. The sorted-list row is especially instructive: checking whether a list is sorted is easy, but sorting a shuffled list requires a method. Computer programs are imperative knowledge written down. Declarative knowledge is used to check whether a program works correctly: that the output of a sorting program is really sorted is tested against the declarative definition.
Thinking that every sentence containing a formula or a definition is imperative knowledge. The sentence “√49 = 7, because 7 · 7 = 49” states a result and its justification; it is declarative. The sentence has no steps, repetition, or stopping condition. A piece of knowledge is imperative only if it states the steps to follow to reach a result.
1.5.5.2Algorithms
Not every kind of imperative knowledge can be given to a machine. “Make a nice meal” is an instruction but does not say which steps to follow. “Add salt until it tastes right” is a step, but how much salt to add is not specified. The instructions a machine can follow must be clear, executable, and finite.
An algorithm is a method that solves a problem in a finite number of clear and executable steps. An algorithm has these properties:
- Clarity: each step has a single meaning; two people carrying out the step do the same thing.
- Executability: each step can really be done with the tools at hand.
- Finiteness: the algorithm stops after a finite number of steps for every input.
- Input and output: the algorithm takes zero or more inputs and produces at least one output.
Algorithms turn imperative knowledge into clear, executable, finite steps. There is no single way to write an algorithm. English sentences, flowcharts, or pseudocode, which resembles a programming language but is not as strict, can be used. In these notes, as in the slides, algorithms are given in short pseudocode. In pseudocode, while means “repeat the lines below it as long as the condition is true,” return means “give back the result and finish,” and print means “write the result on the screen.” Indented lines belong to the while line above them.
Forgetting the stopping condition. The instruction “add 1 to the number and repeat” is clear and executable but never ends. Such a sequence of instructions is not an algorithm; in a program it appears as an infinite loop. Every repeated step must have a stopping condition that will certainly be met some day.
1.5.5.3Approximating a square root
An old and very effective method for finding square roots is attributed to Heron of Alexandria and is also known as the Babylonian method. The idea is this: if a guess is greater than the square root, then x divided by the guess is less than the square root; if the guess is less than the square root, the quotient is greater. The true square root lies between these two numbers. The average of the two is therefore usually a better guess than the guess itself.
Let us see it with an example. Let x = 25 and the guess 13. 25 ÷ 13 ≈ 1.92. The true square root, 5, lies between 13 and 1.92. The average of the two numbers is (13 + 1.92) ÷ 2 ≈ 7.46; 7.46 is much closer to 5 than 13 is. The same operation is repeated with the new guess.
The pseudocode in the slides writes the method in five lines:
x = 25
guess = 1
while |guess * guess - x| > 0.01
guess = (guess + x / guess) / 2
print(guess)The lines do the following, in order:
x = 25: the number whose square root is sought is put into the variable x.guess = 1: a rough starting guess is chosen. Any positive starting value works; 1 is the simplest choice.while |guess * guess - x| > 0.01: the difference between the square of the guess and x, that is, the error, is computed. The vertical bars denote the absolute value: the sign of the difference is dropped and only its magnitude remains. If the error is greater than 0.01, the line inside the loop runs; if not, the loop ends. The value 0.01 is the “close enough” limit; such limits are called a tolerance.guess = (guess + x / guess) / 2: the average of guess and x/guess becomes the new guess. Then we return to line 3 and check the error again.print(guess): when the loop ends, the final guess is written on the screen.
Each run of the loop is called an iteration. The slides trace the algorithm iteration by iteration for x = 25. Figure 1.5.8 shows the journey of the guess on the number line, and Table 1.5.10 shows the values in each iteration.
| Iteration | Old guess | x / guess | New guess | Error |guess² − 25| | Decision |
|---|---|---|---|---|---|
| start | — | — | 1 | 24 | continue |
| 1 | 1 | 25 | 13 | 144 | continue |
| 2 | 13 | 1,9231 | 7,4615 | 30,6746 | continue |
| 3 | 7,4615 | 3,3505 | 5,4060 | 4,2251 | continue |
| 4 | 5,4060 | 4,6245 | 5,0152 | 0,1527 | continue |
| 5 | 5,0152 | 4,9848 | 5,0000 | 0,0002 | halt |
Three things in the table stand out. First, in the first iteration the error rose from 24 to 144. The guess jumped from 1 to 13 and passed 5. This is not a mistake. 1 was a very small guess and x/guess = 25 was very large; their average fell on the other side of the square root. After the second iteration the guess always stays above 5 and gets closer to it with every iteration.
Second, the speed of approach keeps increasing. The error fell from 144 to 30.67, then to 4.23, to 0.15, and to 0.0002. In the last iterations, each iteration roughly doubles the number of correct digits. That is why the method reached four-decimal accuracy in only five iterations. The final guess is not exactly 5 but about 5.00002; its error, however, is far below the tolerance.
Third, the stopping condition looks not at the guess itself but at its square. The algorithm does not know the true value of the square root; if it did, there would be no need to compute. The only thing it knows is the declarative definition: the square of the square root equals x. The stopping condition uses this definition. The imperative method moves forward, and the declarative definition decides when to stop.
The same algorithm is run with x = 2 and guess = 1. How many iterations does it take, and what value is printed? How close is the printed value to the true √2 ≈ 1.41421?
| Iteration | Old guess | x / guess | New guess | guess² | Error | Decision |
|---|---|---|---|---|---|---|
| start | — | — | 1 | 1 | 1 | continue |
| 1 | 1 | 2 | 1.5 | 2.25 | 0.25 | continue |
| 2 | 1.5 | 1,3333 | 1,4167 | 2,0069 | 0,0069 | halt |
The algorithm stops after two iterations and prints about 1.4167. After the second iteration the error is 0.0069; since this is less than 0.01, the loop ends. The printed value is about 1.41667 − 1.41421 ≈ 0.0025 away from the true √2. If a more accurate result is wanted, the tolerance is reduced; for example, if 0.000001 is chosen, the algorithm makes two more iterations and finds 1.414214.
Choosing 0 as the starting guess. When the new guess is computed, x is divided by the guess; if the guess is 0, a division-by-zero error occurs and the algorithm cannot run. A negative x is also a problem: since no real number has a negative square, the error never drops below 0.01 and the loop runs forever. A program that uses the algorithm must check beforehand that the input is positive.
1.5.5.4Euclid’s algorithm
One of the oldest known algorithms appears in Elements, written by the Greek mathematician Euclid around 300 BC. The algorithm finds the greatest common divisor of two positive integers. Although it is about 2,300 years old, it is still used today, for example in reducing fractions and in the encryption methods that secure the internet.
The greatest common divisor (GCD) of two integers is the largest positive integer that divides both of them with no remainder. In the pseudocode of the slides this operation is written GCD(a, b). The remainder of dividing a by b is written a mod b; the mod operation gives the remainder of a division.
A method that applies the definition directly is conceivable: start from the smaller number, try every number downward, and stop at the first number that divides both. For 48 and 18 the trials go 18, 17, 16, … and stop at 6; 13 trials are needed. This method is correct but slow. For 1,000,000 and 999,999 it makes 999,999 trials, because the GCD of these two numbers is 1. Euclid’s method answers the same question in only two iterations.
The pseudocode of Euclid’s algorithm is:
GCD(a, b)
while b ≠ 0
r = a mod b
a = b
b = r
return aThe algorithm works with two variables: a and b. In each iteration of the loop, the remainder of dividing a by b is first computed and put into r. Then the old b takes the place of a, and the remainder r takes the place of b. In this way each iteration turns the problem into the same problem with smaller numbers. When b becomes zero, the loop ends and the value in a is returned.
Let us look briefly at the mod operation. 48 mod 18 is the remainder of dividing 48 by 18. 18 fits into 48 twice: 2 × 18 = 36. What is left is 48 − 36 = 12. So 48 mod 18 = 12. In general one writes a = q × b + r, where q is the quotient, r is the remainder, and 0 ≤ r < b.
Figure 1.5.9 gives a visible interpretation of the algorithm. We want to tile a rectangle 48 units long and 18 units wide exactly with equal squares. The side of the largest square that can be used is the GCD of 48 and 18. As squares with side 18 are cut from the rectangle, a smaller rectangle remains. Each cut corresponds to one iteration of the algorithm. At some point the remaining rectangle is filled exactly with congruent squares; the side of those squares is the number sought.
1.5.5.5Euclid’s algorithm step by step
Let us trace the call GCD(48, 18) line by line. At the start, a = 48 and b = 18.
- Iteration 1. The condition b ≠ 0 is true (18 ≠ 0). r = 48 mod 18 = 12: two pieces of length 18 are taken out of 48, leaving 12. Then a = 18 and b = 12. The smaller number has now become the dividend.
- Iteration 2. 12 ≠ 0 is true. r = 18 mod 12 = 6: one piece of length 12 is taken out of 18, leaving 6. Then a = 12 and b = 6.
- Iteration 3. 6 ≠ 0 is true. r = 12 mod 6 = 0: two pieces of length 6 are taken out of 12, leaving nothing. Then a = 6 and b = 0.
- End of the loop. The condition 0 ≠ 0 is false; the loop ends. The line
return areturns 6.
Figure 1.5.10 shows how many pieces of length b come out of the bar a in each iteration and what is left over. The remainder takes the place of b in the next iteration. The whole run is summarized in Table 1.5.11.
| Iteration | a | b | b ≠ 0? | Division | r = a mod b | New a | New b |
|---|---|---|---|---|---|---|---|
| 1 | 48 | 18 | true | 48 = 2 × 18 + 12 | 12 | 18 | 12 |
| 2 | 18 | 12 | true | 18 = 1 × 12 + 6 | 6 | 12 | 6 |
| 3 | 12 | 6 | true | 12 = 2 × 6 + 0 | 0 | 6 | 0 |
| — | 6 | 0 | false | The loop ends; return a → 6 | |||
Result: GCD(48, 18) = 6. Checking is easy: 48 = 8 × 6 and 18 = 3 × 6. 8 and 3 have no common divisor greater than 1; so there is no common divisor greater than 6 either. The algorithm finished in three iterations. The method that applies the definition directly had made 13 trials.
If GCD(270, 192) is computed with Euclid’s algorithm, how do a, b, and r change in each iteration? What is the result?
| Iteration | a | b | Division | r |
|---|---|---|---|---|
| 1 | 270 | 192 | 270 = 1 × 192 + 78 | 78 |
| 2 | 192 | 78 | 192 = 2 × 78 + 36 | 36 |
| 3 | 78 | 36 | 78 = 2 × 36 + 6 | 6 |
| 4 | 36 | 6 | 36 = 6 × 6 + 0 | 0 |
At the end of the fourth iteration, a = 6 and b = 0; the loop ends and 6 is returned. Check: 270 = 45 × 6, 192 = 32 × 6; 45 and 32 have no common divisor greater than 1. With this result, the fraction 192/270 is reduced by dividing numerator and denominator by 6, giving 32/45.
Swapping the order of the two assignment lines. In the loop, a = b is written first, then b = r. If b = r is written first, the old value of b is lost and the following line a = b puts r into a as well. For 48 and 18, after the first iteration a and b are both 12. In the second iteration 12 mod 12 = 0 comes out; this time a and b are both 0 and the algorithm returns 0 instead of 6. When updating variables in sequence, always check which value is still needed.
1.5.5.6Why does Euclid’s algorithm give the right answer and stop?
That an algorithm gives the right result on a few examples does not show that it works on every input. Two questions are asked about Euclid’s algorithm: why does it always find the right result, and why does it always stop?
Let a and b be positive integers and r = a mod b. The common divisors of a and b are the same as the common divisors of b and r. Therefore GCD(a, b) = GCD(b, r).
The justification of the theorem is as follows. The division is written a = q × b + r; from this we get r = a − q × b. If a number d divides both a and b, it also divides the difference a − q × b, that is, it divides r too. Conversely, if d divides both b and r, it divides the sum q × b + r, that is, a as well. So the two pairs of numbers have the same common divisors. Two pairs with the same common divisors also have the same greatest common divisor.
In the example this can be seen with numbers. The common divisors of 48 and 18 are 1, 2, 3, and 6. The common divisors of 18 and 12 are also 1, 2, 3, and 6. The numbers got smaller but the common divisors did not change. Each iteration of the algorithm shrinks the problem while preserving the GCD. In the last iteration the second number becomes 0. Since every positive number divides 0, the common divisors of a and 0 are the divisors of a, and the largest of them is a itself. That is why the algorithm returns a.
The answer to the question of stopping comes from a property of the remainder. The remainder is always smaller than the divisor: 0 ≤ r < b. Since r takes the place of b in each iteration, b strictly decreases in every iteration. b is a nonnegative integer. A nonnegative integer cannot decrease forever; after decreasing at most b times, it reaches 0. So the loop ends after a finite number of iterations on every input. In practice the number of iterations is far smaller than b. The remainders at least halve every two iterations. So even for numbers below a million, no more than about 30 iterations are needed; the worst-case pair 832,040 and 514,229 finishes in 28 iterations.
What happens if the algorithm is called with GCD(36, 84), that is, with the smaller number given first?
- Iteration 1. 36 mod 84 = 36; 84 does not fit into 36 at all, and the whole number remains. Then a = 84 and b = 36. The numbers have swapped places.
- Iteration 2. 84 mod 36 = 12 (84 = 2 × 36 + 12). a = 36, b = 12.
- Iteration 3. 36 mod 12 = 0. a = 12, b = 0 and the loop ends.
The algorithm returns 12. The order of the numbers does not change the result; only one extra iteration is spent swapping the numbers. The algorithm therefore does not need to require the inputs to be given in order.
Thinking that calling the algorithm with b = 0 gives an error. In the call GCD(15, 0) the loop condition is false at the first check; the loop never runs and 15 is returned. This is correct, because 15 divides both 15 and 0. The real problem is the call GCD(0, 0): since every number divides 0, the greatest common divisor is undefined, but the algorithm returns 0. That is why the definition of the algorithm says “two positive integers.”
1.5.6Computational thinking
The square-root and Euclid algorithms were ready-made solutions to ready-made problems. Real-life problems, however, often arrive in a muddle: “We need a system that makes it easier for students to register for courses.” The path from such a request to a working program goes through several tasks. The problem is split into parts, the similarities between the parts are seen, what matters is separated from what does not, and finally the steps are written. This way of thinking is called computational thinking. This part takes the four components of computational thinking one by one and in the end combines them in an example.
1.5.6.1What is computational thinking?
Computational thinking is the approach of turning problems into structures that a computer or a person can solve systematically. It has four components: decomposition, pattern recognition, abstraction, and algorithm design.
The concept was popularized by a short paper that the computer scientist Jeannette Wing published in 2006. According to Wing, computational thinking is a fundamental skill that everyone, not only programmers, should learn, just like reading, writing, and arithmetic. Thinking computationally does not mean thinking like a computer. A computer only does what it is told; computational thinking is the skill of working out what to tell it.
Figure 1.5.11 numbers the components in an order, but in practice this order is not rigid. While an algorithm is being written, a new subproblem may be noticed and one returns to decomposition. A pattern may determine what abstraction focuses on. The four components work together and feed one another.
Traces of computational thinking can also be seen in daily life. A cook divides a big meal into preparation, cooking, and serving stages; that is decomposition. A teacher uses the same extra worksheet for students who make similar mistakes every year; that is pattern recognition. A city map shows the streets, not the colors of the buildings; that is abstraction. A recipe is also an algorithm.
1.5.6.2Decomposition
Decomposition is breaking a large, complex problem into smaller subproblems that are easier to solve. The input and output of each subproblem are defined separately.
The example in the slides is an online registration system. Users will register from a web page, their information will be stored, and a confirmation email will be sent to them. It is hard to think of this system as a single piece: it is not clear where to start, and when an error occurs it cannot be found where it is.
Figure 1.5.12 shows two levels of decomposition. At the first level the system is divided into four main subtasks. At the second level some subtasks are divided again. Each leaf at the bottom of the tree is a small job that can be written and tested on its own. For example, the “format check” might be a small piece that only looks at whether the email address contains an @ sign and whether the password is at least eight characters.
| Subtask | Input | Output |
|---|---|---|
| User input | Email and password | Signed in, or an error message |
| Form validation | The fields in the form | “Valid,” or a list of the faulty fields |
| Registration | Validated form data | A new record in the database and a registration number |
| Notification | Email address and registration number | Confirmation email sent to the user |
Table 1.5.12 shows the real value of decomposition: the subtasks are linked to one another through their inputs and outputs. The output of form validation is the input of registration. The registration number that registration produces is the input of notification. When these links are written down explicitly, three important benefits appear.
- Separate development and testing. Each subproblem can be developed and tested separately. The person writing the notification part does not have to know how form validation works; they only need to know what information will come to them.
- Clear interfaces. The inputs and outputs of the subproblems are defined explicitly. When one part is changed, the other parts are not affected as long as its input and output stay the same.
- Early view of dependencies. It is noticed early which part waits for which. Notification cannot run before registration is finished, because it needs the registration number. This information determines the order in which the jobs are done.
A department wants a program that prepares a seating plan for a final exam. There are 250 students; the halls have capacities of 80, 80, 60, and 40. How is the problem decomposed, and how are the students distributed among the halls?
| Subtask | Input | Output |
|---|---|---|
| Read the student list | File taken from the student information system | List of 250 students |
| Read the halls | Hall names and capacities | List of 4 halls, total capacity |
| Check the capacity | Number of students, total capacity | “Enough” or “not enough” warning |
| Assign the students | Student list, hall list | A hall and seat number for each student |
| Print the lists | Assignment result | The list to be posted at the door of each hall |
- Capacity check. 80 + 80 + 60 + 40 = 260 ≥ 250; the capacity is sufficient and 10 seats remain empty.
- Assignment. If the halls are filled in order, 80 students go to the first hall, 80 to the second, and 60 to the third. These three halls hold 80 + 80 + 60 = 220 students. The remaining 250 − 220 = 30 students go to the fourth hall; there 40 − 30 = 10 seats remain empty.
Decomposition also revealed a dependency: the assignment cannot be done before the capacity check. If there were 270 students, the capacity check would give a “not enough” warning and the assignment would never start.
Listing the subtasks only by name, without writing their inputs and outputs. A list that says “validation,” “registration,” “notification” does not say what the parts give one another. When the parts are written separately and put together, one may expect a phone number while another sends an email address. For each subtask the question “what does it take, what does it give?” must be answered.
1.5.6.3Pattern recognition
Pattern recognition is finding the similarities and repetitions among different problems or among different parts of one problem.
Let us return to the registration system. The system will register three kinds of people: students, staff, and visitors. A separate registration form could be designed for each. But when the forms are put side by side, something catches the eye.
Figure 1.5.13 shows the repeating structure. Three of the four fields of the three forms are the same. This is a pattern. Noticing the pattern has practical value. The code that checks that the name field is not left empty, that the ID number has 11 digits, and that the email address is written in the correct format does not have to be written three times. It is written once and used in all three forms. When an error is found in the ID number check, it is fixed in a single place.
Patterns are seen not only in data but also in operations. The average computation and Euclid’s algorithm do different jobs, but both follow the same pattern: repeat an operation as long as a condition is true, and give the result when the condition becomes false. The square-root algorithm fits this pattern too. This pattern is so common that every programming language has a special structure for it, the loop.
A dormitory administration wants a program that computes the monthly water, electricity, and natural gas bills. Let this month’s values be as follows (the prices are for illustration): water 12 m³, unit price 30 TL, fixed fee 40 TL; electricity 180 kWh, unit price 3 TL, fixed fee 60 TL; natural gas 90 m³, unit price 8 TL, fixed fee 20 TL. What pattern is there in the three computations?
- Water. 12 × 30 + 40 = 360 + 40 = 400 TL.
- Electricity. 180 × 3 + 60 = 540 + 60 = 600 TL.
- Natural gas. 90 × 8 + 20 = 720 + 20 = 740 TL.
- Pattern. All three computations fit the same template: amount = consumption × unit price + fixed fee. Only three numbers change.
The total bill is 400 + 600 + 740 = 1,740 TL. Once the pattern is noticed, the program contains a single computation rule instead of three separate computations, and this rule is run three times with different numbers. If the dormitory later wants to add the internet bill, it is enough to give the same rule three new numbers.
Mistaking a superficial similarity for a pattern. A student number and an ID number both consist of digits, but one is an 11-digit national ID number with its own rules and the other is a number specific to the university. Putting them through the same check gives wrong results. A pattern means similarity not only in appearance but also in meaning and rules.
1.5.6.4Abstraction
Abstraction is focusing on the details that matter for a purpose and hiding unnecessary details. The product of abstraction is a simplified model of reality.
Pattern recognition finds the repeating structure; abstraction gives this structure a name and separates it from the details. In the registration example, the common fields of the three types are gathered into a single “Person” model.
Figure 1.5.14 shows the result. The Person model has three fields. A student record has all of Person’s fields; in addition it has a student number. Staff add a unit, and visitors add a visit date. Most of the system, for example the notification part that sends email, works only with the Person model. The notification part does not have to know whether the person it emails is a student or a staff member; it needs only the email field. The differences show only where they are needed, for example in the part that prepares the student list.
A good abstraction factors out the repeating structure without losing the important differences. Putting the student number into the Person model as well would be wrong, because a visitor has no student number and this field would stay empty in most records. Removing the email field from the model would also be wrong, because the notification part could not work. The measure of abstraction is the purpose: the detail that serves the purpose stays, and the detail that does not is hidden.
What features of the building does the fire escape plan posted in the corridors of a faculty building show, and which does it hide? Why does this abstraction work?
- Purpose. In a fire, the plan must let someone in the building get outside by the shortest route.
- Details kept. Corridors, stairs, exit doors, the locations of fire extinguishers, and the “You are here” marker.
- Details hidden. The furniture in the rooms, the color of the walls, the number of windows, whom the rooms belong to, the year the building was built.
- Why does it work? In a moment of panic, the reader’s attention goes only to the way out. If the furniture were on the plan, the drawing would be crowded and the way out would be found later.
The plan an architect uses for the same building is far more detailed; it also shows wall thicknesses and electrical lines. There is no single “right” model of a building. Every purpose calls for its own abstraction.
Thinking that abstraction means “deleting details.” In abstraction, details do not disappear; they are hidden. The student number is not visible in the Person model but stays in the student record. When needed, for example when a student’s number is looked up, that detail is reached again. A model that really deletes a needed detail becomes useless.
1.5.6.5Algorithm design and testing
Algorithm design is writing the solution of a problem as clear, ordered steps. Testing is checking whether the written steps produce the expected output on different inputs. Each pair of an input and an expected output chosen for checking is called a test case.
Algorithm design is not a job that is finished in one go; it proceeds in a cycle.
The cycle in Figure 1.5.15 has five stages.
- Creating examples. Before writing code, a few inputs and the expected outputs for them are prepared. For the average: the expected output for the input 70, 85, 60, 75 is 72.5. The expected output is computed by hand; the algorithm’s result will be compared with it.
- Writing the steps. The solution is written in pseudocode.
- Tracing by hand. The pseudocode is run on paper, line by line, with the prepared sample input. At each step the values of the variables are written into a trace table. The tables used in these notes for the Turing machine, the square root, and Euclid’s algorithm are tables of this kind.
- Testing the boundaries. Besides normal inputs, the smallest, the largest, and invalid inputs are tried. Inputs of this kind are called edge cases. Most bugs show up on these inputs.
- Fixing. When a bug is found, it is not only the symptom but the root cause of the bug that is fixed. Then the cycle starts again: the corrected algorithm is traced again with all the examples.
Let us follow this cycle with an example. Suppose the following algorithm, which finds the average of a list of grades, has been written:
total = 0
count = 0
while there is a grade to read
total = total + grade
count = count + 1
print(total / count)The algorithm does exactly the same computation as in Example 1.5.1: the total and the counter start at 0, each grade is added to the total and the counter goes up by one; at the end the total is divided by the counter. Now let us test it with inputs of different kinds.
| Kind | Input | Expected output | Algorithm’s output | Result |
|---|---|---|---|---|
| Normal | 70, 85, 60, 75 | 72.5 | 290 / 4 = 72.5 | passed |
| Smallest | 100 (a single grade) | 100 | 100 / 1 = 100 | passed |
| Extreme values | 0, 100 | 50 | 100 / 2 = 50 | passed |
| Invalid | (no grades) | “No grades entered” warning | 0 / 0: division by zero error | failed |
Table 1.5.13 caught a bug in the last row. If no grade is entered, the loop never runs; the total and the counter stay at 0 and the last line divides 0 by 0. The program crashes. Tests with normal inputs would never have revealed this bug.
There are two ways to fix the bug. The first is to remove the symptom: “if the counter is 0, take the average to be 0.” The program no longer crashes but says something wrong: the average of a student who has no grades at all appears as 0 and the student is taken to have failed the course. The second is to fix the root cause. The root cause is this: the average of an empty list is undefined, and the algorithm never considered this case. The right fix is to handle this case separately:
total = 0
count = 0
while there is a grade to read
total = total + grade
count = count + 1
if count = 0
print("No grades entered")
else
print(total / count)In the corrected algorithm, the if line makes a decision: if the counter is 0, the warning is printed; otherwise (else) the average is computed. When the algorithm is traced again with the four test cases, the first three again give 72.5, 100, and 50; the fourth now prints the expected warning.
Testing only with normal inputs. Hundreds of randomly chosen ordinary lists would not reveal the empty-list bug even once. What matters is not the number of test cases but their variety. A good test set contains at least one normal, one smallest, one extreme, and one invalid input.
1.5.6.6All four together: a grade calculator
How do the four components of computational thinking work together in solving a problem from start to finish? Let us see this with a small problem. An instructor wants a simple tool that computes students’ end-of-term scores. The score is 40% of the midterm grade plus 60% of the final exam grade. A student whose score is 50 or above passes.
Decomposition. The problem is split into four subtasks. Reading the grades: the input is the student’s midterm and final grades, the output is two numbers. Validating the grades: the input is two numbers, the output is “valid” or “invalid.” Computing the score: the input is two valid grades, the output is the score. Decision: the input is the score, the output is “passed” or “failed.”
Pattern recognition. The midterm and final grades follow the same rules: both must be between 0 and 100. The validation rule is written once and applied to both grades. The score computation is also a pattern: each grade is multiplied by its own weight and the results are added. If an assignment grade is added later, one more term is added to the same template.
Abstraction. For the tool, a student consists only of two numbers: the midterm and the final. The student’s name, department, attendance record, or the answers on the exam paper do not affect this computation and have no place in the model.
Algorithm design. The steps are written in pseudocode:
read(midterm, final)
if midterm < 0 or midterm > 100 or final < 0 or final > 100
print("Invalid grade")
else
score = (40 * midterm + 60 * final) / 100
if score >= 50
print(score, "passed")
else
print(score, "failed")In the score formula, the percentages are written as 40 and 60 instead of 0.4 and 0.6, and the result is divided by 100. The two forms are the same in mathematics. However, computers cannot store decimal numbers like 0.4 exactly in binary, and small rounding differences can occur. For example, the computation 55 × 0.4 + 72 × 0.6 may give 65.19999… instead of 65.2 on a computer. Multiplying with whole numbers and dividing at the very end reduces this risk.
The grade calculator is tested with the following inputs. What does the tool print for each input?
| Kind | Midterm | Final | Score | Output |
|---|---|---|---|---|
| Normal | 55 | 72 | (40 × 55 + 60 × 72) / 100 = (2.200 + 4.320) / 100 | 65.2 passed |
| Normal | 40 | 45 | (1.600 + 2.700) / 100 | 43 failed |
| Boundary | 80 | 30 | (3.200 + 1.800) / 100 | 50 passed |
| Extreme value | 100 | 100 | (4.000 + 6.000) / 100 | 100 passed |
| Extreme value | 0 | 0 | (0 + 0) / 100 | 0 failed |
| Invalid | −5 | 70 | Midterm below 0 | Invalid grade |
| Invalid | 60 | 105 | Final above 100 | Invalid grade |
The third row is the most instructive. The score is exactly 50 and the rule says “50 and above passes.” If score > 50 had been written by mistake instead of score >= 50 in the algorithm, this student would appear to have failed. Normal inputs never reveal this difference; only the input exactly on the boundary does.
In this small example each of the four components did a job. Decomposition divided the work into parts and showed which part waits for which. Pattern recognition prevented the validation rule from being written twice. Abstraction left out unneeded student information. Algorithm design and testing caught, before any code was written, a bug that could have caused a student on the boundary to fail unfairly.
1.5.7Summary
- Computation is the processing of data according to rules; it is not limited to arithmetic. Searching, sorting, decision making, transformation, and communication are computation too. Every computation has an input, a process, and an output; the process uses the resources time, memory, energy, and communication.
- The building blocks of computation are mathematics, logic, data, algorithms, hardware, and a programming language. An algorithm is an idea; a program is the writing of that idea in a particular language.
- Computer science studies the representation and processing of information and the methods of solving problems. Its main areas of interest are abstraction, algorithms, systems, and people and society. The responsibilities of technology are accessibility, privacy, fairness, and sustainability.
- From Babbage and Lovelace to Turing, from Colossus and ENIAC to today’s phones, the basic ideas have stayed the same; as hardware became faster and smaller, these ideas spread to wider fields.
- In a fixed-program machine the job is determined by the physical layout of the machine. In a stored-program machine the instructions are kept in memory like data; loading a new program gives the machine a new job. This idea made the general-purpose computer possible.
- The Turing machine is an abstract model of computation made up of a tape, a read/write head, a state, and transition rules. Each step is determined only by the (state, symbol read) pair. The machine that adds 1 turns 111 into 1000 in four steps.
- The universal Turing machine reads the rules of another machine given on its tape and imitates it. This is the theoretical foundation of the stored-program idea.
- The limits of computers come from time, memory, energy, computability, data quality, and the model. Computability limits such as the halting problem cannot be overcome with any hardware.
- Declarative knowledge says what is true; imperative knowledge says how to reach a result. An algorithm turns imperative knowledge into clear, executable, finite steps.
- The square-root method proceeds by averaging the guess and x/guess and stops when the square of the guess gets close enough to x; for x = 25 it reaches 5.0000 in five iterations.
- Euclid’s algorithm uses the equality GCD(a, b) = GCD(b, a mod b); because the remainder shrinks in every iteration, it always stops. GCD(48, 18) gives 6 in three iterations.
- Computational thinking combines four components: decomposition (breaking into subproblems, defining inputs and outputs), pattern recognition (finding repetitions), abstraction (focusing on what matters and hiding the rest), and algorithm design (clear, ordered steps). The design is tested with normal, smallest, extreme, and invalid inputs; it is the root cause of a bug that is fixed, not its symptom.
1.5.8Key terms
The key terms of this chapter are listed below.
- computation
- input
- computer science
- accessibility
- privacy
- fairness
- sustainability
- fixed program
- stored program
- general purpose
- von Neumann architecture
- Turing machine
- tape
- symbol
- read/write head
- state
- transition rule
- universal Turing machine
- computability
- halting problem
- declarative knowledge
- imperative knowledge
- algorithm
- pseudocode
- iteration
- tolerance
- infinite loop
- Euclid's algorithm
- greatest common divisor (GCD)
- remainder
- modulo (mod)
- computational thinking
- decomposition
- pattern recognition
- abstraction
- algorithm design
- testing
- test case
- edge case
- trace table
1.5.9Test Yourself
The Turing machine that adds 1 to a binary number is run with 1111 (binary 15) on the tape; the head is at the rightmost digit. In how many steps does the machine halt, which rules are used, and what is left on the tape?
Answer
Since all four digits are 1, rule 1 is applied four times; each time 0 is written and the head moves left. The tape becomes 0000 and the head arrives at the blank cell to the left of the number. In the fifth step □ is read; rule 3 writes 1 and the machine halts. 10000 is left on the tape: 16 = 15 + 1. The number of steps is 4 + 1 = 5; rule 2 is never used.
The parity machine is run with 10010 on the tape. What is the state after each symbol, and what does the machine write at the end?
Answer
The state starts as “even.” 1 is read: odd. 0: odd. 0: odd. 1: even. 0: even. In the sixth step the blank cell is read; since the state is “even,” E is written and the machine halts. The tape becomes 10010E. The string has two 1s, and two is even.
GCD(105, 75) is computed with Euclid’s algorithm. What are a, b, and r in each iteration? How many iterations does it take, and what is the result?
Answer
Iteration 1: 105 = 1 × 75 + 30, r = 30; a = 75, b = 30. Iteration 2: 75 = 2 × 30 + 15, r = 15; a = 30, b = 15. Iteration 3: 30 = 2 × 15 + 0, r = 0; a = 15, b = 0. The loop ends; 15 is returned after three iterations. Check: 105 = 7 × 15, 75 = 5 × 15; 7 and 5 have no common divisor greater than 1.
The square-root algorithm is run with x = 9 and guess = 1. What are the guess and the error after each iteration? After how many iterations does the algorithm stop?
Answer
At the start the error is |1 − 9| = 8. Iteration 1: (1 + 9) ÷ 2 = 5, error |25 − 9| = 16. Iteration 2: (5 + 1.8) ÷ 2 = 3.4, error |11.56 − 9| = 2.56. Iteration 3: (3.4 + 2.6471) ÷ 2 ≈ 3.0235, error ≈ 0.1417. Iteration 4: (3.0235 + 2.9767) ÷ 2 ≈ 3.0001, error ≈ 0.0005. Since the error drops below 0.01, the algorithm stops after four iterations and prints about 3.0001.
Is each of the following pieces of knowledge declarative or imperative? (a) Water boils at 100 °C at sea level. (b) To find out whether a number is divisible by 3, add its digits; if the sum is divisible by 3, so is the number. (c) The area of a rectangle is the product of its side lengths.
Answer
(a) is declarative; it states a fact. (b) is imperative; it gives the steps to follow to reach a result: add the digits, check the sum. (c) is declarative; it defines what the area is. This definition can be used to compute an area, but the sentence does not describe a method, it states an equality.
How do a mechanical music box that plays a single song with the pins on its cylinder and a smart speaker that plays songs downloaded from the internet differ in terms of program?
Answer
The music box is fixed-program: the song it plays is the physical arrangement of the pins on the cylinder; for another song the cylinder must be changed. The smart speaker is stored-program: the processor inside runs software stored in memory and can gain new features through software updates. The smart speaker itself is still designed for particular jobs and the user cannot load their own programs onto it; so it is not counted as a general-purpose computer.
Which limit of computers does each of the following situations illustrate? (a) A student tries to write a tool that tells in advance whether any program will enter an infinite loop. (b) A program that makes 109 attempts per second can try all the possibilities of a 50-bit key in about 13 days in the worst case. (c) On a survey form, 250 was entered in the age field and the average age came out meaningless.
Answer
(a) is the computability limit; this is the halting problem and such a general tool cannot be written. (b) is the time limit: 250 ÷ 109 ≈ 1.13 × 106 seconds, about 13 days; faster hardware shortens the time, but each bit added to the key doubles it again. (c) is the data-quality limit; even if the algorithm works correctly, faulty input gives a wrong result.
An algorithm that counts the words in a text is to be tested. Besides a normal sentence, which boundary and invalid cases should be tried? Give at least four cases and the expected result for each.
Answer
A sample test set: empty text → 0; a single word (“Hello”) → 1; more than one space between words (“one␣␣two”) → 2; spaces at the beginning and end of the text (“␣one two␣”) → 2; text consisting only of spaces → 0. If the algorithm increments the counter at every space, it gives a wrong result in the last three cases. The root cause is counting spaces instead of words; the right fix is to count the places where a word starts.
1.5.10Further reading
- J. M. Wing, “Computational Thinking”, Communications of the ACM, 49(3), 2006: a short paper, in three pages, that explains why computational thinking is a basic skill for everyone and popularized the concept.
- J. V. Guttag, Introduction to Computation and Programming Using Python (3rd ed., MIT Press, 2021), Chapter 1: the distinction between declarative and imperative knowledge, the square-root method, and fixed-program and stored-program machines are explained in language very close to that of these notes.
- C. Petzold, The Annotated Turing (Wiley, 2008): explains Turing’s 1936 paper line by line and builds up the Turing machine, the universal machine, and computability without requiring mathematical background.
- M. Sipser, Introduction to the Theory of Computation (3rd ed., Cengage, 2012), Chapters 3–4: a precise mathematical treatment of Turing machines and the halting problem; for those who want to continue the subject at an advanced level.
1.5.11References
- J. M. Wing, “Computational Thinking”, Communications of the ACM, 2006.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, MIT Press.
- A. B. Downey, C. Mayfield, Think Java, Green Tea Press.
- M. Sipser, Introduction to the Theory of Computation, Cengage.
Related pages: Slides · Study questions · Turing Machine simulator · Glossary · © Sercan Külcü. All rights reserved.