COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics
Last Class Solving many little problems to avoid thinking about too much at once! A tiny bit about java
Today What is programming? How computers think A tiny bit more about java: The structure of a program
ASSIGNMENT 1 First Java Assignment COMP-202A, Fall 2012, All Sections Due: September 24th, 2012 (23:30)
Part 1: What Is Programming?
Programming and Computers In order to understand what programming is, we need to know what a computer is COMP-202 - Introduction 6
Programming and Computers In order to understand what programming is, we need to know what a computer is A computer is a machine that executes lists of instructions We feed a list of instructions to the computer and the computer executes them The computer may apply the instructions on additional information fed to the computer (the input) The computer may produce information as a result of executing this list of instructions (the output) COMP-202 - Introduction 7
Programming and Computers Programming a computer involves two things: 1) Designing lists of instructions that will make the computer solve specific problems (a.k.a. writing your program) 2) Having the computer execute the instructions (a.k.a. running your program) COMP-202 - Introduction 8
Why do we want to program? Before we go any further, it's important to answer the question: What's the benefit of programming? COMP-202 - Introduction 9
Why do we want to program? COMP-202 - Introduction 10
Benefits of programming Programming computers allows us to sleep much more easily knowing that nothing ever could go wrong. Our programs will always work perfectly and will never crash or make any sort of mistakes. COMP-202 - Introduction 11
Actually...maybe not Anyone used Windows Vista? COMP-202 - Introduction 12
Benefits of programming All jokes aside, generally we program computers because we either can't or don't want to do the task ourselves. Some reasons: -very repetitive task -arithmetic of large numbers -searching through millions of documents -having someone help us without having to bother a real human -playing a game against a computer -researching information -Using all modern life infrastructure COMP-202 - Introduction 13
Giving a computer instructions A very good way to think about giving a computer instructions is the following: 1)First figure out what is given in the problem and where it is you are trying to go. 2)Figure out a broad picture of how you want to get from your start to the goal. When you do this, you should figure out, at each step, what you are given, and what you want to produce. Now you have several, smaller problems. You can solve the smaller problems the same way. COMP-202 - Introduction 14
Example: Planning Dinner Start: We need to construct a path from the start to the goal Goal: COMP-202 - Introduction 15
Example: Planning Dinner Start: Goal: COMP-202 - Introduction 16
Giving a computer instructions At each partial step, we need to make sure we have very precisely determined what we have at the moment and what we need to produce in that step. For example: Step 1)Shopping: We have : a recipe a burning desire to eat food money We want to produce: raw ingredients COMP-202 - Introduction 17
Giving a computer instructions Here we can also notice that one of the things we have is not really needed to solve this partial problem. For example: Step 1)Shopping: We have : a recipe a burning desire to eat food money We want to produce: raw ingredients COMP-202 - Introduction 18
Giving a computer instructions At each partial step, we need to make sure we have very precisely determined what we have at the moment and what we need to produce in that step. Step 2)Chopping: We have : raw ingredients We want to produce: chopped ingredients What is very important about this? COMP-202 - Introduction 19
Giving a computer instructions Step 2)Chopping: We have : raw ingredients We want to produce: chopped ingredients The input of step 2 is part of the output of step 1. This means that we can use it. If step 2 required something else (for example, if we also needed to buy knives), then this wouldn't be a complete solution. COMP-202 - Introduction 20
Giving a computer instructions At each partial step, we need to make sure we have very precisely determined what we have at the moment and what we need to produce in that step. Step 3)Cooking We have : chopped ingredients We want to produce: cooked food And we've found a path from one to the other. COMP-202 - Introduction 21
Giving a computer instructions When you are giving instructions to a computer, most of the time, you will repeat this divide and conquer process. For example: Shopping could be split into: 1)Pick up onions 2)Pick up bread 3)Pick up meat 4)Wait in line at the cash register 5)Pay the cashier etc. COMP-202 - Introduction 22
Input vs Output : Input The input to a program is what goes into it. It is whatever is given to the program or problem. This is anything that is necessary to solve it. COMP-202 - Introduction 23
Input vs Output : Output The output from a program is what comes from it. This is anything that is produced as a result of the program running COMP-202 - Introduction 24
Example: f(x) = 2x The input to this mathematical function is a number The output to this function is a number Note: Input is similar to domain in math. Output is similar to range We have to judge by context whether this function is being used on integers, real numbers, or imaginary numbers. (Or something completely different!) In Java, we will explicitly write what the domain and range are. COMP-202 - Introduction 25
Example: f(x,y) = 2x + 3y What is the input and output? COMP-202 - Introduction 26
Example: f(x,y) = 2x + 3y The input to this mathematical function is two numbers - - x and y The output is 1 number. The sum of 2x and 3y COMP-202 - Introduction 27
Giving the instructions to a computer Once you have mapped out a solution to a problem in small enough instructions, you can program a computer to execute the instructions
Two things to remember about computers 1)They require very specific instructions: -You can't tell a computer to cook dinner. It has to be much more detailed!
Two things to remember about computers 2)They interpret instructions very literally. -No sense of idioms as we do in human languages.
Amelia Bedilia COMP-202 - Introduction 31
Amelia Bedilia Draw the drapes Make a sponge cake Pitch the tent COMP-202 - Introduction 32
Programs (1) A computer program is essentially a list of instructions telling a computer what to do The computer is stupid in that it is just following the instructions without knowing what it is doing. Thus you must be very precise and omit no details. COMP-202 - Introduction 33
Programs (2) Computer problems will have an input and an output as well. If you omit the proper instructions or include the wrong instructions, generally 4 things can happen: 1)You get incredibly lucky and on that particular input it works anyway 2)The program gives the incorrect output 3)The program crashes 4)The program goes on forever and ever COMP-202 - Introduction 34
Case 1 Sometimes you will give the computer the wrong instructions, but it will work anyway on a particular input. For example, suppose I teach a computer to compute x- squared, and define x^2 as being equal to x + x. Of course this is wrong, but sometimes it will give the right answer. When would this still lead to the right answer? COMP-202 - Introduction 35
Case 1 If x = 0 or x = 2 then x*x = x+x It's always very important when you test any program you write to test it on as many possible inputs as possible! COMP-202 - Introduction 36
Case 2 The program gives the wrong output This would happen in the previous example on any input other than x = 0 or x=2 COMP-202 - Introduction 37
Case 3 Sometimes the program will crash. This could happen if we defined x^2 as being 1 / x and the input was x = 0 The computer might not know how to divide a number by zero. COMP-202 - Introduction 38
Case 4 The program goes on forever and ever Suppose I defined x^2 in terms of x^2. Sometimes (amazingly!) that will actually work, but let's say I told the computer You should compute x-squared by computing x-squared COMP-202 - Introduction 39
Giving a computer your instructions This step consists of translating your human words into a language the computer understands Kind of like learning a foreign language. But there are some key differences. Sentences in human languages can often have many interpretations. COMP-202 - Introduction 40
Human and Computer Languages Consider the following English sentence: "The lady hit the man with a baby" Does this mean 1)A lady hit a man who had a baby? (That s not nice!) 2)A lady used a baby to hit a man? (Good lord!) 3)A lady and a baby ganged up on a man and hit him. (Kids today!) Computer statements, on the other hand, always have only one possible interpretation although sometimes no one knows how a computer will interpret something! COMP-202 - Introduction 41
Human and Computer Languages One of the challenges is to learn the different interpretations the computer will give to commands. The computer will not normally tell you how it is interpreting things. It is up to you to figure it out, both by looking at your code and observing the output. COMP-202 - Introduction 42
Computer Instructions Luckily, most computer instructions are very simple! A=B If (a is true) do something Else do something else End
Solving Complex Tasks Sometimes, we want the computer to perform complex tasks Writing a detailed list of precise instructions for this complex task would be very difficult There are just too many instructions for humans to manage Remember, we only want to think about 4 or 5 (and at absolute most 7) instructions at a time. COMP-202 - Introduction 44
Solving Complex Tasks Solution: Break down the complex task into a series of simpler tasks and figure out the input and output of each step; if the simpler tasks are still too complex, break them down into even simpler tasks. Write a list of instructions for each of the simpler tasks The list of instructions for each of the simpler tasks can be used as a single instruction in the list of instructions that performs the original task While considering each subtask, don't worry about how you will solve the other parts. COMP-202 - Introduction 45
Summary so far It's critical to only be thinking about a few things at a time. When we are trying to solve a problem on a computer, we need to figure out the input and output first. Then we should construct a path from the input to output, with various checkpoints in between. COMP-202 - Introduction 46
Java! Now, let's go over our very first program! COMP-202 - Introduction 47
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } COMP-202 - Introduction 48
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } One thing to notice is all these { and } These are used to denote blocks of code. The purpose of a block is mainly to help the programmer keep track of what parts of code are related. COMP-202 - Introduction 49
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } {'s always mark the beginning of a block (or segment) of code. Each { always has a corresponding } to mark the end. You can tell which corresponds to which because the first { opened, will correspond with the last } COMP-202 - Introduction 50
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } Try at home: What happens if you remove the final }, so that there are not matching braces? What happens if you add an extra } at the end so that there are 3 }s? COMP-202 - Introduction 51
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } Most (but not all) of the time, right before a { will be some code specifying what kind of block of code something is. For the first {, the code is public class HelloWorld COMP-202 - Introduction 52
class in Java public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } One of the key units of organizing things in Java is called a class. A class can have many different things in it which we'll see throughout the term. COMP-202 - Introduction 53
class in Java public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } Here we are saying: I want to create a class called HelloWorld and I want it to be public The first { signifies the start of the definition of the class The final } signifies the end of the definition of the class COMP-202 - Introduction 54
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } On the second line we have another { In this case, the code before is defining a method COMP-202 - Introduction 55
methods in Java public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } A method is also a key unit of organization in Java. COMP-202 - Introduction 56
methods in Java public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } Here we are saying: I want to create a method called main There are several other words (public, static, void, String[], args) that we'll talk about later. COMP-202 - Introduction 57
methods in Java public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } The second { signifies the start of the method called main. The first } signifies the end of the definition of the method called main. COMP-202 - Introduction 58
methods in Java public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } Since the definition of the method called main is inside the definition of the class called HelloWorld, it means that the method main is a part of the class HelloWorld. COMP-202 - Introduction 59
Methods and classes Almost every line of code you write in Java will be inside a class. This helps keep things nicely organized. Almost every line of code you write in Java will also be inside of a method. This also helps keep things nicely organized. Every method you ever write, will be part of a class. COMP-202 - Introduction 60
main method The main method is a very particular method. When you run a Java program, you actually run a Java class When you do this, the execution of your program will always start at the beginning of the method called main inside whatever class you run. COMP-202 - Introduction 61
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } Inside of a method, you can put many statements or commands. The highlighted line is an example of a statement. All statements in Java end in a semi-colon. COMP-202 - Introduction 62
Java Program: Hello World public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); } } The command System.out.println is a way to print something to the screen. It will print everything between ( and ) as long as it's on 1 line. COMP-202 - Introduction 63
Summary: -Important to break problems down into many pieces -Input / ouput -Classes and methods are just 2 of the ways that Java helps us to organize things. These are important because they'll help make sure we don't need to think about too much at once. COMP-202 - Introduction 64
Part 2: How a Computer Works
Hardware and Software (1) A computer system consists of both hardware components and software Hardware consists of the physical, tangible parts of a computer Cases, monitors, keyboard, mouse, chips Rule of thumb: If you can take it in your hands and it is part of a computer system, then it is hardware It is the hardware which executes the instructions Software: Programs and data that they use A computer requires both hardware and software Software cannot run without hardware; instructions are useless unless they are performed by someone / something COMP-202 - Introduction 66
Hardware and Software (2) Hardware will not do anything without software telling it what to do Therefore, each is essentially useless without the other COMP-202 - Introduction 67
An (old) Personal Computer Monitor / screen (output) Speakers (output) Case; contains: CPU Memory Disk drives... Keyboard (input) Mouse (input) COMP-202 - Introduction 68
Central Processing Unit (CPU) The "operation/action" part of the computer's brain Basically controls the information / data in a computer Perform instructions Arithmetic operations Logic operations Decisions The instructions it understands are much simpler and fine-grained than those we have seen in previous examples COMP-202 - Introduction 69
Memory Memory holds the data Think of a filing cabinet Main memory: Most of it is called RAM, which stands for Random-Access Memory Data has to be in main memory so that the CPU can access it Volatile: its contents are lost when the program terminates or when the computer shuts down Secondary storage: Hard drive / CD / DVD / Blu-Ray disc / USB memory stick Persistent: its contents will not be lost when the computer shuts down This is where you keep the data for long-term storage Secondary storage has much slower access times than main memory COMP-202 - Introduction 70
taking notes; packing a box remembering what Dan said 2 minutes ago remembering your name COMP-202 - Introduction 71
taking notes; packing a box (CPU) remembering what Dan said 2 minutes ago (RAM) remembering your name (secondary storage) COMP-202 - Introduction 72
How do we store things? Computer memory is electronic. It's just a bunch of wires! All it can recognize is on (current goes through) and off (no current goes through) Using many of these on/off switches together, we can encode many things. For example, we can store whether it is morning or afternoon using the following encoding: if the 1 st switch is on, then it must be PM. If the 1 st switch is off, then it must be AM COMP-202 - Introduction 73
Storing whether it is afternoon or morning Pick one electrical switch in memory. Whenever it is on it is AM Whenever it is off it is PM A computer stores billions or trillions of these switches By combining many of these, we can control many things. (Note: This is just an example. Your computer probably stores this in an entirely different way.) COMP-202 - Introduction 74
Encoding the day of the week How could we encode the day of the week? If we just use 1 switch, there will not be enough information. How many switches will we need? COMP-202 - Introduction 75
Storage is Exponential In general, if there are n possible values to store, we can encode it using log 2 (n) switches Of course, there is no such thing as a fraction of a switch, so we will always have to round up. Put another way, if we have n switches, we can store 2 n values COMP-202 - Introduction 76
Bits = Switch 1 bit is the same thing as a switch It has one or two values on or off For simplicity of notation, we will often just refer to these as 1 (on) and 0 (off) If you like, you could call them true/false, yes/no, oui/non, or cats/dogs COMP-202 - Introduction 77
Byte = 8 bits A byte is simply 8 bits Question: How many possible values can we store in a byte? COMP-202 - Introduction 78
Other Memory Units A kilobyte is 2 10 bytes (1024 bytes) A megabyte is 2 10 kilobytes (1024 kilobytes) Strangely, a gigabyte is just 1,000,000,000 bytes COMP-202 - Introduction 79
Practice Exercises 1) How many bits does it take to encode the day of the month? 2) How could you encode the letters of the alphabet? 3) How could you encode a 3 letter word? 4) How would you encode a sentence? COMP-202 - Introduction 80
Main Memory Organization address 9278 9279 9280 9281 9282 9283 9284 9285 cell Main memory is divided into many memory locations (or cells) Each memory cell has a numeric address which uniquely identifies it Each cell contains a data value (for example, 22) COMP-202 - Introduction 81
Bits and Bytes In a computer, data values are stored as sequences of bits 1 bit: most basic unit of memory 1 byte = 8 bits 1 byte can therefore represent 2 8 = 256 different values In memory, one cell contains one byte, not one bit 9278 22 9278 00010110 9279 7 9279 00000111 COMP-202 - Introduction 82
Number systems (decimal vs. binary) The way we usually count (1, 2, 3, 4, 5, 6...) corresponds to a decimal number system. Each number position (digit) represents a power of 10 multiplied by an integer between 0 and 9. 6 = 6 x 10 0 31 = 3 x 10 1 +1 x 10 0 0.5 = 0 x 10 0 + 5 x 10-1 In the binary number system, each number position (bit) represents a power of 2 multiplied by an integer between 0 and 1. 6 = 1 x 2 2 + 1 x 2 1 + 0 x 2 0 = 110 31 =? COMP-202 - Introduction 83
Devices Devices are hardware components which the CPU can access and control Input devices are used to feed information to the computer Output devices is what the computer uses to give information back to the user Some devices are both input and output devices Examples of devices: Cards (Video card, sound card, network card,...) Optical (CD / DVD / Blu-Ray) drives USB ports... COMP-202 - Introduction 84
Motherboard Acts as a bridge between the CPU, memory, disks, and other devices Data transfers taking place between the hardware components of a computer take place via the motherboard COMP-202 - Introduction 85
Program Execution and Hardware Keyboard READ Main Memory DISP 17 18 Monitor LOAD STORE 17 18 CPU ADD 17 18 COMP-202 - Introduction 86
Hardware Interaction Central Processing Unit (CPU) Monitor Keyboard Main Memory Hard Drive CD-RW COMP-202 - Introduction 87
Program Execution (fetch-execute cycle) A program tells the CPU how to manipulate and/or move information The CPU repeatedly performs the three following operations: Reads the next instruction in the program Figures out what the instruction means add two values? load some value from memory? store some value in memory? compare two numbers?... Performs the instruction This is called the fetch-execute cycle COMP-202 - Introduction 88
Program Execution (2) Suppose you want to write a program that reads a number from the keyboard, adds 1 to it, and displays the new value to the screen This program might consist of the following instructions: READ a value from the keyboard and store it in memory location x LOAD the value stored in memory location x into the CPU ADD 1 to the value stored in the CPU STORE the value currently in the CPU back into memory location x DISPLAY the value stored in memory location x to the screen COMP-202 - Introduction 89
Program Execution and Hardware Keyboa rd READ Main Memory DISP 17 18 Monitor LOAD STORE 17 18 CPU ADD 17 18 COMP-202 - Introduction 90
Part 3: Programming Languages
Programming Languages (1) We need to expresses our ideas in a form that a computer can understand: a program A programming language specifies the words and symbols that we can use to write a program e.g. red belongs to English; rouge belongs to French A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements e.g. Banana red and in not a valid statement in English. COMP-202 - Introduction 92
Programming Languages (2) Computers are very intolerant of incorrect programming language statements Humans are much more tolerant of incorrect natural language statements You understand The kiten is cute even though kitten is mispelled. COMP-202 - Introduction 93
Syntax and Semantics The syntax rules of a language define what words and symbols are valid in this language, and how they can be combined to make a valid program The kiten is cute is not syntactically correct. The semantics of a program statement define what those words, symbols, and statements mean (their purposes or roles in a program) Banana red and. is not semantically correct. COMP-202 - Introduction 94
Machine Language Each instruction that a CPU understands is represented as a different series of bits The set of all instructions that a CPU understands directly forms the machine language for that CPU Each CPU type understands a different machine language In other words, for each different model of CPU, a given series of bits could mean a different instruction For example, on an x86-compatible CPU (Intel, AMD), the series of bits 10101010 could mean ADD, while on a PowerPC CPU (old Macs, PlayStation 3) it could mean LOAD COMP-202 - Introduction 95
Machine Language Example Here are the first 20 bytes of a machine language program that: asks the user to enter an integer value using the keyboard reads this value from the keyboard adds one to this value, and displays the new value to the screen 01111111 01000101 01001100 01000110 00000001 00000001 00000001 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000010 00000000 00000011 00000000 More the 6500 bytes in total! COMP-202 - Introduction 96
Do you think it's fun or easy to write a binary program? COMP-202 - Introduction 97
Machine Language Disadvantages Very tedious and confusing: machine language is extremely difficult for humans to read Error-prone If you change one bit from 1 to 0 (or vice-versa), or forget a bit, your program's behavior will likely be not even close to what you expected Moreover, errors are hard to find and correct Programs are not portable Running the program on a different processor or CPU requires a complete rewrite of the program COMP-202 - Introduction 98
High-Level Languages (1) To make programming more convenient for humans, high-level languages were developed No CPU understands high-level languages directly Programs written in these languages must all be translated in machine language before a computer can run them (that's what a compiler is for) Basic idea: Develop a language that looks like a mix of English and mathematical notation to make it easier for humans to read, understand, and write it For each CPU type, develop a program that translates a program in high-level language to the corresponding machine language instructions (a compiler) COMP-202 - Introduction 99
High-Level Language Example #include<stdio.h> int main(void) { int v; printf("enter an integer value: "); scanf("%i", &v); v = v + 1; } printf("new value (old value + 1): %i\n", v); return 0; COMP-202 - Introduction 100
Compilers vs. Interpreters COMP-202 - Introduction 101
Compilers Source code (high-level) Compiler (to CPU 1) Compiler (to CPU 2) Binary code (CPU 1) Binary code (CPU 2) CPU 1 CPU 2 COMP-202 - Introduction 102
Interpreters (1) An interpreter is another kind of program. It takes source code and translates it into a target language However, the target language instructions it produces are executed immediately No executable file is created COMP-202 - Introduction 103
Interpreters (2) Source code (high-level) Interpreter (for CPU 1) Interpreter (for CPU 2) CPU 1 CPU 2 COMP-202 - Introduction 104
Java combines a compiler with an interpreter Java compiler (javac, included in JDK 6) takes source and translates it into bytecode foo.java (Java) javac foo.class (bytecode) foo.class can than be executed using an interpreter, the Java Virtual Machine (JVM) COMP-202 - Introduction 105
Programming Errors A program can have three types of errors Compile-time errors: the compiler finds problems with syntax and other basic issues Run-time errors: a problem occurs during program execution, and causes the program to terminate abnormally (or crash) Division by 0 Logical errors: the program runs, but produces incorrect results celcius = (5.0 / 9.0) * fahrenheit - 32; // Incorrect equation; should be // (5.0 / 9.0) * (fahrenheit 32) COMP-202 - Introduction 106
Compiling and Running Programs Type your program using a text editor (not a word processor) or an IDE (Integrated Development Environment) Save your program: e.g. foo.java Compile the program If there are syntax errors, the compiler will not generate the target language program; it will report the errors instead In this case, fix the program, save it, and try again Run the program and observe the results If there are logical errors or run-time errors, they will be detectable in this step In this case, fix the program, save it, recompile it, and try again COMP-202 - Introduction 107
Development Life Cycle Syntax errors Logic and run-time errors Write program Compile program 0 errors Run program Errors may take a long time to debug! Important Note: When you compile for the first time and see 150 errors, do not despair. Only the first 1 or 2 errors are relevant. Fix those and compile again. There should be fewer errors (like 50). Repeat until there are no more errors. COMP-202 - Introduction 108
Summary Computers can only process information in binary (electrical switches) Binary = hard to read and write High level languages were designed to make this easier Compilers vs Interpreters COMP-202 - Introduction 109
Next Class Java! How to write things to the screen How to get text from a user How to perform arithmetic in Java COMP-202 - Introduction 110