Introduction to Computer Science
In questa pagina 10
This note covers the opening lessons of the Foundations of Computer Science course: the key questions (what is computer science, a computer, a program, programming, an algorithm), the historical and theoretical background, and the notion of algorithm with worked examples. The hardware side is in Computer ArchitectureModern computers follow the von Neumann model: a CPU (ALU, control unit, registers, cache) driven by a clock runs a fetch-decode-execute cycle on programs and data stored in the same memory; memory is a hierarchy from fast, small and volatile (registers, cache, RAM) to slow, large and persistent (SSD, disk, tape); CPU, memory and I/O talk through a bus made of data, address and control lines on the motherboard.Computer Architecture →, how programs are translated in Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals →, and how data are encoded in Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →.
1. First questions
The course starts from five questions: what is computer science, a computer, a program, programming, an algorithm. The slides open with a quote: computer science is no more about computers than astronomy is about telescopes. The computer is the tool; the subject is computation, i.e. which problems can be solved by a mechanical procedure and how efficiently.
2. Historical foundations
Hilbert and the decision problem
- At the end of the 19th century mathematics began to question its own foundations.
- David Hilbert proposed 23 fundamental mathematical problems to be solved during the 20th century.
- Among them, the decision problemis there a universally valid method that determines with certainty the truth or falsity of any statement in formal logic.
- Hilbert was confident: in mathematics there is no ignorabimus ("we will not know").
Turing and Church
- About 1936 Alan Turing and Alonzo Church showed that such a universal procedure does not exist: "undecidable" propositions exist.
- In doing so the concept of algorithm was introduced: a sequence of "elementary" operations making up a computational procedure.
- In 1936 Turing introduced the Turing machine, a theoretical model of computation: an imaginary computer, a universal machine able to solve any computable problem.
- His ideas laid the foundation for modern computers and artificial intelligence.
The Turing machine
A mathematical model describing how a computer operates. Components:
| Component | Role |
|---|---|
| Tape | theoretically infinite, divided into cells; holds the input (a string of symbols) |
| Head | reads and writes the symbol in the current cell, and moves right (R) or left (L) |
| Control unit | current state , set of states , tape alphabet , transition function |
| Final states | an accepting state (halt-accept) and a rejecting state (halt-reject) |
The machine can read or write a symbol, move right or left (or not move, N), and change state until the computation is complete.
A transition rule has the form where:
- is the current state and the symbol read on the tape;
- is the new state and the symbol to write;
- is the movement direction (blank symbol shown as a square).
Why it matters (slide summary):
- It showed that many problems can be solved by following an algorithm (a step-by-step procedure turning an input into an output).
- It defined the concept of computability: what is computable (solvable by a machine) and what is not.
- It is the foundation of the theory of algorithms and of programming languages: every program is a sequence of elementary instructions, like the operations of a Turing machine.
- It is a theoretical model, but the foundation of modern computers: real ones are far more complex, yet reading, writing, memory and control derive from it.
Path shown on the slide: theoretical idea (1936) -> electromechanical machines and early calculators -> electronic circuits and microprocessors -> modern computers and complex software -> Internet, artificial intelligence and future technologies.
3. Theoretical foundations
Problem complexity
Not all problems are the same. Decidable problems are those for which an algorithm exists. Complexity classes group problems by the computational resources (time, space) needed to solve them. Some problems are practically difficult: theoretically solvable, but they need enormous resources.
From easiest to hardest:
| Class | Meaning | Example on the slide |
|---|---|---|
| LOGSPACE | logarithmic space, very little memory and time: the easiest problems | |
| P | polynomial time: efficient problems | sorting a list of numbers, finding shortest paths |
| NP | nondeterministic polynomial: verifying a solution is quick and easy, finding it is difficult | Traveling Salesman Problem; factoring large integers (cryptography), not known to be in P |
| EXPTIME | time grows exponentially with the input size | |
| EXPSPACE | exponential space: enormous time, even longer than the age of the universe | universe simulation (EXPSPACE / EXPTIME) |
Key characteristics stressed on the slide:
- recognizing some problems is easy, solving them is not;
- computational resources grow exponentially with the complexity;
- some problems are easy to verify but hard to solve (find a solution);
- some problems are efficiently solvable (polynomial time);
- some need only logarithmic or relatively low space.
Complexity tells how "expensive" a problem is and helps choose the best approach.
Formal languages
A formal languagea precisely defined language in which the rules, or productions, determine which strings are valid is generated by a grammar, i.e. a set of grammatical productions.
Example over the alphabet with productions
Applying the first rule repeatedly and then the second gives , , , ... : the grammar represents an infinite set of well-formed strings defined by the rules.
The Chomsky hierarchy
Noam Chomsky classified languages into four categories according to the type of grammar generating them, from the most general to the most specific.
| Type | Language class | Form of productions | Example language | Automaton |
|---|---|---|---|---|
| 1 | Universal (unrestricted) | with , contains at least one non-terminal | strings are countably infinite, recognizable by a Turing machine | Turing machine |
| 2 | Context-sensitive | with | (same number of a, b, c) | Linear bounded automaton |
| 3 | Context-free | with , | (same number of a and b) | Pushdown automaton |
| 4 | Regular | , , with , | strings over ending with a | Finite automaton |
The three notions fit together: grammars define the rules that generate strings, languages consist of valid strings, automata are machines that recognize languages. The classification is used to describe and classify programming languages, compilers and parsers, regular expressions, and calculation and verification models.
Shannon: bits, circuits and information
Claude Shannon (1916-2001) gave the theoretical foundations of digital circuits (bits with values 0 and 1) and of information theory.
- Logic gates work on bits (0 = FALSE/OFF, 1 = TRUE/ON):
| A | B | AND | OR |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 |
NOT inverts a single bit (0 -> 1, 1 -> 0).
- Reliable transmission: sender -> encoding -> channel (with noise) -> decoding -> receiver. The objective is to transmit information correctly and efficiently. This leads from information theory to computer networks.
Information and entropy
- Information is that which, for an observer facing a situation with at least two possible occurrences, overcomes uncertainty and resolves an alternative.
- In communication with a finite alphabet of symbols, the information associated with a transmitted symbol is the reduction of the a priori uncertainty about it.
- The information linked to a symbol (the uncertainty of an experiment) is
where is the probability of that symbol being transmitted.
- A bit is the amount of uncertainty in an experiment with only two equiprobable outcomes (check: gives ).
The slide quotes Shannon on the name: von Neumann advised calling the uncertainty function "entropy", because it was already known by that name in statistical mechanics and because nobody knows what entropy really is.
4. Computers and programs
- A computer (from Latin computare, to calculate) is an electronic device that processes data by following a sequence of instructions. It is good at repetitive tasks (calculations, text formatting), complex operations done quickly and accurately (controlling machinery, managing information systems), and realistic images and sounds in games.
- Its capabilities depend not only on the hardware but also on the software it runs. Software consists of programs: sequences of instructions telling the computer how to perform specific tasks.
- A computer is a machine that can process data (numbers, words, sounds, ...) and interact with external devices (monitor, keyboard, mouse, network, ...) by running programs.
- Programs are sequences of instructions the computer can execute and decisions it can make, to perform a certain activity (formatting text pages, complex math, playing chess, ...).
At their core programs are made of simple operations and decisions:
| Operations | Decisions |
|---|---|
| read a value from memory | if a value is negative, continue execution from a different instruction |
| add two numbers | |
| output a character to a printer | |
| display a pixel on the screen |
Combining these elementary steps, computers perform remarkably complex tasks.
5. Programming
- A program describes in great detail to the computer the sequence of steps required for a specific task.
- Programming is the activity of designing, implementing, testing and maintaining a program.
- Simply using a computer does not require programming (it uses programs written by others: games, web browser, e-mail, messaging, media player, word processing, graphics). A computer professional usually programs, though it is not the only skill needed.
- Goal of the course: write simple programs, initially in Python and later in Java.
Why two languages
| Python | Java | |
|---|---|---|
| Style | highly interactive: write and run code immediately; ideal for experimentation and rapid prototyping | needs more setup: the program is written completely, then translated into executable form |
| Reason | it is an interpreted language | it is primarily a compiled language |
| Learning | easier to learn and use; hides many implementation details | needs a deeper understanding of programming concepts; more explicit and structured |
| Errors | rapid development, but some errors are only detected when the program runs | many errors are detected before execution, so large programs are easier to maintain |
Learning both shows different programming styles and the trade-offs of software development. An interpreted languagea language whose programs are executed by an interpreter that processes the source code or an intermediate representation at run time and a compiled languagea language whose programs are translated into executable code before execution are explained in Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals →.
6. Computational thinking
- Programming is a way of thinking. First goal: learn to program in Python. Second goal: learn to think like a computer scientist.
- This way of thinking combines features of three disciplines:
- mathematics: like mathematicians, computer scientists use formal languages to denote ideas (specifically computations);
- engineering: they design things, assembling components into systems and evaluating trade-offs among alternatives;
- natural science: they observe the behavior of complex systems, form hypotheses and test predictions.
- The course starts from the most basic elements: how Python represents numbers, letters and words, arithmetic operations, and the vocabulary of programming (operator, expression, value, type), needed to follow the course, to communicate with other programmers and to use virtual assistants.
7. Algorithms
What a computer can solve
Two sample problems:
- Given a series of landscape photographs, which landscape is the most relaxing?
- After depositing 20,000 euros in an account earning 5% interest annually, how many years until the balance doubles?
The first cannot be solved by a computer: it is ambiguous for humans and computers alike, and cannot be rigorously solved unless a definition of "relaxing landscape" is given that uniquely compares two landscapes. A computer can only solve problems that could, in principle, also be solved manually: it is simply faster, does not make mistakes and does not get distracted. The second problem can certainly be solved manually, by doing some calculations.
Definition
An algorithm is the description of a method for solving a problem that
- consists of a finite sequence of executable steps;
- comes to a conclusion in a finite number of steps.
A computer can only solve problems for which an algorithm is known. The word comes from Al-Khwarizmi, a Persian mathematician of the 9th century AD.
Example: doubling an investment
Problem: deposit at annual interest ; find the number of years for the balance to reach double the initial amount. More than one algorithm can solve a problem.
Algorithm 1: enumeration. Write the balance year after year until it reaches double the initial amount. Known data: , ; the balance of year follows from year :
The table on the slide goes from 20,000.00 (year 0) to 41,578.56 (year 15); in year 14 the balance is 39,598.63 and in year 15 it is 41,578.56, so the answer is 15 years.
Algorithm 2: mathematical formulation. and we need :
The enumeration algorithm, split into executable steps:
- A. Current year , current balance .
- B. Repeat steps C and D while the balance is less than 40,000, then go to step E (the flow chart below makes the test explicit: "balance < 40000?").
- C. Add 1 to the current year.
- D. New balance = current balance multiplied by 1.05 (add 5%).
- E. The result is the value of the current year.
Properties of the method (what makes it an algorithm):
- it gives precise instructions on what to do at each step and which step comes next;
- it is executable: each step can be implemented concretely (if the rate used in step D depended on unknown future economic factors, the method would not be executable);
- it terminates in finite time: at each step the balance increases by at least 1,000 units, so it finishes in fewer than 20 steps.
Flow charts
Simple algorithms are often shown as flow charts with these symbols:
| Symbol | Meaning |
|---|---|
| rounded box | algorithm start / end |
| rectangle | algorithm step |
| diamond | binary decision (true / false branches) |
| arrow | oriented arc (flow of control) |
The investment algorithm as a flow chart: start -> A (year = 0, balance = 20000) -> B (balance < 40000?) -> if true: C (increment year), D (increment balance), back to B; if false: E (result is the value of the year) -> end.
Example: Sieve of Eratosthenes (276-196 BC)
Problem: list all primes . A prime is a positive integer greater than 1 that is not the product of two smaller positive integers (it can be divided only by 1 and itself). Primes : 2, 3, 5, 7, 11, 13, 17, 19, 23. The RSA cryptography algorithm is based on prime numbers.
Idea: instead of testing each number for primality, eliminate the multiples of known primes.
Algorithm (step form, ):
- A. Write the integers from 2 to in ascending order and set the support variable .
- B. Until , repeat steps C and D, then perform step E.
- C. Remove all multiples of greater than () from the sequence.
- D. Set to the next integer in the list that has not been removed.
- E. End: the primes are the integers not removed.
Worked example with :
- A: 2 3 4 5 6 7 8 9 10 11, .
- B: . C removes 4, 6, 8, 10 -> 2 3 5 7 9 11. D: .
- B: . C removes 9 -> 2 3 5 7 11. D: (as shown on the slide).
- B: , stop. E: primes are 2, 3, 5, 7, 11.
Flow chart: start -> A (list numbers 2..n, ) -> B (?) -> true: C (remove multiples of ), D ( next integer not removed), back to B; false: E (primes are the integers not removed) -> end.
Example: divide and conquer
Problem: find the maximum integer in a non-empty set of integers.
Idea: if the set has one element only, that element is the max. Otherwise split the set into two sets A and B, find the max in A (maxA) and in B (maxB) with the same method, and return .
Example on the slide with the set 3 7 2 3 8 1 5: it is split into A = (3, 7, 2) and B = (3, 8, 1, 5); halves are split again until single elements remain, and results are combined pairwise: A gives 7, B gives 8 (with 3 and 8 giving 8, and 1 and 5 giving 5), and the final max is 8.
Flow chart: start -> does N have one element only? true -> max -> end; false -> split N into A and B -> find max in A -> find max in B -> max = max(maxA, maxB) -> end. The two "find max" boxes apply the same algorithm again.
8. Advanced problems
Traveling Salesman Problem (NP-complete)
Given a set of cities and the distances between each pair, find the shortest path a traveling salesman must follow to visit all the cities once and return to the starting city. It is a typical case study of theoretical computer science and complexity theory (the slide notes it is not for this class).
Halting problem (undecidable)
Question: can we write a program that determines, for any program P and input I, whether P will eventually stop (halt) or run forever?
Answer: no. Alan Turing proved in 1936 that it is undecidable: no algorithm can solve it in general.
9. What algorithms are for
- Identifying an algorithm is a prerequisite for solving a problem, with or without a computer.
- Writing a program usually means translating an algorithm into a programming language.
- Before writing a program one must identify and describe an algorithm.
- Defining algorithms and measuring their efficiency are important topics of computer science and of this course.
10. Symbols used in the course slides
Icons used in the slides: common mistakes, productivity tips, quality tips, advanced topics, references to topics explored later, Java/Python syntax rules, news notes.
Versione ripasso
Core idea. Computer science is about problems, algorithms and computation; the computer is only the tool.
- Decision problem (Hilbert): decision problemis there a universally valid method that determines with certainty the truth or falsity of any statement in formal logic. Turing and Church showed that no such universal procedure exists (about 1936).
- Algorithm: a finite sequence of executable steps that reaches a conclusion in a finite number of steps. A computer can only solve problems for which an algorithm is known.
- Turing machine (1936): tape, head (reads and writes, moves L, R or N), control unit with state . Transition: , with .
- Complexity classes, easiest to hardest: LOGSPACE, P (polynomial, efficient), NP (quick to verify, hard to find, e.g. Traveling Salesman), EXPTIME, EXPSPACE.
- Chomsky hierarchy: type 1 unrestricted (Turing machine), type 2 context-sensitive (linear bounded automaton, ), type 3 context-free (pushdown automaton, ), type 4 regular (finite automaton).
- Information of a symbol: . One bit is the uncertainty of an experiment with two equiprobable outcomes ( gives ).
- Computer: processes data and interacts with devices by running programs; its capabilities depend on hardware and software.
- Programming: designing, implementing, testing and maintaining a program. The course uses Python first, then Java.
Worked algorithms.
- Doubling an investment (20,000 at 5%): enumeration with gives 15 years; the formula gives the same answer.
- Sieve of Eratosthenes: list 2 to , set ; while remove the multiples of and set to the next integer not removed. The integers left are the primes (for : 2, 3, 5, 7, 11).
- Divide and conquer, maximum: one element is the maximum; otherwise split the set, find both maxima and return .
Not solvable or not feasible in general: the Halting problem (undecidable, Turing 1936); the Traveling Salesman Problem (NP-complete); a "most relaxing landscape" (ambiguous, no definition).
Common mistakes: confusing computer science with computers; calling an NP problem impossible (it is only not known to be in P); treating an undecidable problem as merely hard; running an ambiguous problem without a precise definition.