1 CS102 Unit 2 Sets and Mathematical Formalism Programming Languages and Simple Program Execution
2 Review Show how "Hi!\n" would be stored in the memory below Use decimal to represent each byte Remember how we terminate a string 0 1 2 3 4 5 6 7
BEING PRECISE 3
4 Humans and Computers Humans understand instructions differently than computers Humans easily tolerate ambiguity and abstract concepts using context to help. Add a pinch of salt. How much is a pinch? Steph Curry can shoot the lights out. It s a bear market Computers must be precise, only executing welldefined instructions (no ambiguity) and operating on digital information which is finite and discrete (a fixed number of options)
5 Set Introduction As we just saw, computer scientists and engineers need a certain level of precision and formalism when we express ourselves One tool from discrete mathematics that helps us with this is sets A set is an unordered collection of items (usually referred to as elements or members) Can be used to specify exactly what options we are considering, processing, inputting or outputting
6 Expressing Sets 0 99 Sets are usually denoted by an upper case letter with elements listed inside curly braces { }) Example: Let S be the set of the first 10 positive integers S = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 For large sets, enumerating all the elements may be difficult so we can use an ellipse to communicate the pattern for generating the members -1 S 9 7 8 2 4 1 3 11 13 6 10 5 12 Example: Let T be the set of odd integers between 0 and 100 T = 1, 3, 5,, 99
7 Common Sets A few common sets: N = Natural Numbers = { 0, 1, 2, 3 } Z = Integers = {, 3, 2, 1, 0, 1, 2, 3, } Z + = Positive Integers = { 1, 2, 3, } Z = Negative Integers = {, 3, 2, 1} Q = Rational Numbers (e.g. 4/5, -2/3, etc.) R = Real Numbers R + = Positive Reals R = Negative Reals A few symbols: = element of (e.g. 2 N, 3 Z) = not an element of (e.g. 2.5 N, i N, )
P(x)=true P(x)=false P(x)=true P(x)=true P(x)=true 8 Set Builder Notation Sometimes listing all the elements of a set could be arduous if not impossible Instead we can use set-builder notation where we describe a set by listing what property (properties), P, must be true about its member elements Example: S = x P(x) The symbol is read as 'such that' We would read this as, "S is the set of all x, such that x meets the property(-ies), P Thus we could have described the set of the first 10 positive integers as: S = x x is an integer, 1 x 10 A comma can be read as 'AND' where both properties need to hold All potential elements x x S
P(x)=true P(x)=false P(x)=true 9 Restricting the Universe With sets, "universe" refers to all the possible elements being considered for membership in the set (i.e. all integers, all real numbers, all students in a class, etc.) When we use set-builder notation like: S = { x P(x) }, we are saying x can take on all options in the universe and then we'll check if P(x) is true It often helps to restrict the universe to a smaller set: S = x x is an integer, 1 x 10 could be rewritten as S = x Z 1 x 10 Read: S is the set of all integers, x, such that x is between 1 and 10 What's the difference if we left out the restriction: S = x 1 x 10 All potential elements x Z x Z S
10 Using Formula You can also use formula to express the items in the set: Recall: T = 1, 3, 5,, 99 This can be written with set-builder notation as: T = 2n + 1 n N, n < 50 Here we say, "T is the set of values that are 1 more than two times n such that n is a natural number less than 50 (i.e. 0 to 49)"
11 Practice Examples A is the set of all real numbers greater than 10 A = B is the set of the first 20 non-negative multiples of 3 B = C is the set of all integers whose square is greater than 50 C =
12 Practice Examples A is the set of all real numbers greater than 10 A = x R x > 10 B is the set of the first 20 non-negative multiples of 3 B = 3i i N, i < 20 C is the set of all integers whose square is greater than 50 C = i i Z, i 2 > 50
13 ALGORITHMS & PROGRAMMING LANGUAGES
14 Algorithms Algorithms are at the heart of computer systems, both in HW and SW They are fundamental to Computer Science and Computer Engineering Informal definition An algorithm is a precise way to accomplish a task or solve a problem A more formal definition: An ordered set of unambiguous, executable steps that defines a terminating process Software Hardware
15 Algorithm Representation An algorithm is not a program or programming language Just as a story may be represented as a book, movie, or spoken by a story-teller, an algorithm may be represented in many ways Flow chart Pseudocode (English-like syntax using primitives that most programming languages would have) A specific program implementation in a given programming language
16 Syntax and Semantics Programming languages have syntax and semantics Syntax: refers to the rules of a language for how it will be expressed and parsed (decomposed) Specific to the language Semantics: refers to the meaning of what is written Often transcends the language (same concept in many language) Example: A sentence The syntax refers to the proper grammatical way of writing a sentence (at least a subject and verb, capitalizing the first letter and ending with a period) The semantics refer to the meaning conveyed by the sentence C Code Example if (condition) { action } is the syntax. The semantics (meaning) is the action will only be performed if condition is true
17 A First Program Go to: http://cpp.sh Enter this program to print "Hello!" five times #include <iostream> int main() { for(int i=0; i < 5; i++){ std::cout << "Hello!" << std::endl; } return 0; } Introduce some syntax errors Introduce a semantic error C++ syntax requires statement to end with a semicolon (;) and grouped by curly braces { }. Removing one would lead to a syntax error. A semantic error is when I tell the computer to do the wrong thing but it still meets the correct syntax. Change "i=0" to "i=1" and see it print only 4 times rather than the desired 5.
18 CODE ORGANIZATION AND SEQUENCE OF EXECUTION
19 Sequence & Executability Let's learn a bit more about program execution by using another language named Scratch http://scratch.mit.edu Write a Scratch program to walk forward, turn right, then walk forward again Remember computers need executable steps How far forward? Turn right by how much?
20 Sequence & Executability Scratch provides a "menu" of executable options You must compose a program from that "menu" Create the program shown to the right and then click the green flag to the left of the red stop sign What happens? Click the green flag again What happens?
21 Explicitness Computers do only what you tell them, no more, no less What additional details might we want to instruct the computer? Where to start and what direction to face? To provide some delay between steps Remember computers execute code very quickly compared to what a human can see
22 Sequential Execution Notice Program is executed 1 operation at a time in sequential fashion Each operation is ordered (a definite first, second, third, operation) 1 2 3
23 Organizing Code - Functions Notice the repetition of a common sequence of code executed multiple times Move 100 steps Wait 1 second Programming languages generally allow code to be organized into chunks that perform user-defined tasks Usually called functions, procedures, methods, subroutines, etc. "Functions" are an important way to organize your code and help avoid repetition, prevent mistakes (changing one occurrent rather than many), making the code more understandable to another human, etc.
24 Sequence of Execution With Functions We can define a function and then replace all its occurrences in the main program Do we execute sequentially (top-down) Not Really We execute the main program sequentially, then when we encounter a function/subroutine we jump, execute it sequentially, and then return and resume back in the main program 8 9 1 2 3 4 5 6 7 Do we execute Sequentially?? 4a 4b 1 2 3 4 5 6 7 7a 7b
25 Sequence of Execution With Functions Our function "DelayedMove" is useful for the simple task we gave you to implement What might make it more useful and "general" so that we could reuse it in the future more easily? The ability to generalize how many steps to take and how long to wait might be helpful We call these "input parameters" Each time we want to use the function we can specify different values for the parameters then the operations inside the function will use whatever values we provide Example: First execution of DelayedMove steps = delay = Second execution of DelayedMove steps = delay =
26 C/C++ Program Format/Structure Comments Anywhere in the code C-Style => "/*" and "*/" C++ Style => "//" Compiler Directives #includes tell compiler what other library functions you plan on using 'using namespace std;' -- Just do it for now! main() function Starting point of execution for the program All code/statements in C must be inside a function Statements execute one after the next and end with a semicolon (;) Ends with a 'return 0;' statement Other functions printname() is a function that can be "called"/"invoked" from main or any other function /* Anything between slash-star and star-slash is ignored even across multiple lines of text or code */ // Anything after "//" is ignored on a line // #includes allow access to library functions #include <iostream> #include <cmath> using namespace std; void printname() { cout << "Tommy Trojan" << endl; } // Execution always starts at the main() function int main() { cout << "Hello: " << endl; printname(); printname(); return 0; } Hello: Tommy Trojan Tommy Trojan
27 (Optional Instructor may skip due to time constraints) PROGRAMMING LANGUAGES
28 Computer Abstractions Recall that all computer programs must be converted to 1's and 0's (aka machine code) Similar to translating from one spoken language to another Imagine you need to give a speech in front of a crowd that does not speak your native language. How could you do it? SW Compilers / Interpreters HW High Level Languages: Python / Java / C++ Assembly / Machine Code Logic Gates Transistors Applications OS Processor / Memory / I/O Voltage / Currents Libraries
29 Compiled vs. Interpreted Languages Compiled (Natively) Requires code to be converted to the native machine language of the processor in the target system before it can be run Analogy: Taking a speech and translating it to a different language ahead of time so the speaker can just read it Faster Often allows programmer closer access to the hardware Interpreted Requires an interpreter program on the target system that will interpret the program source code command by command to the native system at run-time Analogy: Speaking through an interpreter where the speaker waits while the translator interprets Better portability to different systems Often abstracts HW functionality with built-in libraries (networking, file I/O, math routines, etc.) https://www.youtube.com/watch?v=qaj7no1huqa
30 Best of Both Worlds? Many languages used for web and desktop apps (e.g. Java and Python) will compile their code to an intermediate form (aka bytecode) Then an interpreter can be used to execute the byte code faster than interpreting the high-level language directly New interpreters can be provided for new devices (platforms) Other languages like C/C++ compile their code directly to a form that can be executed and run on the device Machine Code for ios (ARM) ARM Proc. High-Level Language Compiler ByteCode Interpreter Machine Code for PC (x86) PC Proc.
31 High Level Languages http://www.digibarn.com/collections/posters/tongues/computerlanguageschart-med.png
32 So What Do Compilers Do First, check for correct grammar (aka syntax) Second, check for appropriate meaning where it can be inferred (aka semantics) Perform the translation into appropriate output language For C/C++ this is binary (machine code)
33 Why C++ Because it is used widely Java, C, C++, C#, and Python are commonly the top 5 Because it is "close" to the hardware Makes it fast Makes it flexible (Near direct control of the HW) Makes it dangerous (Near direct control of the HW) In fact, many other languages are themselves written in C/C++ Because if you learn C++ you can likely learn MOST languages very quickly Because that's what we use in CS 103
34 A Live Demo Sort an array of integers from N-1 to 0 [9,999 9,998 9,997 3 2 1] => [1 2 3 9,997 9,998 9,999] With a Python script (interpreted) With C++ (compiled natively) With a "built-in" Python library function that does the same task we just wrote manually (different algorithm) a = range(n) a.reverse() a.sort() // built-in sort implementation (non-interpreted) Note: Algorithms can make all the difference!