comp 110 note set #1: problem solving, algorithms, …cov/comp110s15/notes/noteset01_intro.pdf ·...

30
COMP 110 1 Note Set #1 COMP 110 Note Set #1: Problem Solving, Algorithms, Programs, Intro to Java Outline of Note Set #1 Part I Problem Solving, Algorithms, Computer Programming (The Big Picture) Algorithms and Problem Solving Role of Programming Languages Like Java What Kinds of Operations Can Computer Hardware Perform How Is A Software Application Created Using a Programming Language Using or Executing The Application After it is Created Characteristics of Good Programs Part II Intro to the Java Programming Language (The Nuts and Bolts) The Hello World Program Class Definitions Method Definitions Balancing and Nesting of Grouping Characters Statements Simple Program with Both Input and Output Data Types Constants Variables Arithmetic Assignment Simple Program Development Process Part III Overview of the CS Major and the Relationship between Comp Sci and Math

Upload: hanhan

Post on 06-Sep-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 1 Note Set #1

COMP 110 Note Set #1: Problem Solving, Algorithms, Programs, Intro to Java Outline of Note Set #1 Part I Problem Solving, Algorithms, Computer Programming (The Big Picture)

• Algorithms and Problem Solving • Role of Programming Languages Like Java • What Kinds of Operations Can Computer Hardware Perform • How Is A Software Application Created Using a Programming Language • Using or Executing The Application After it is Created • Characteristics of Good Programs

Part II Intro to the Java Programming Language (The Nuts and Bolts)

• The Hello World Program • Class Definitions • Method Definitions • Balancing and Nesting of Grouping Characters • Statements • Simple Program with Both Input and Output • Data Types • Constants • Variables • Arithmetic • Assignment • Simple Program Development Process

Part III Overview of the CS Major and the Relationship between Comp Sci and Math

Page 2: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 2 Note Set #1

Noteset #1 Part I Quick Summary of Problem Solving and Programming

• A problem is a question you want to know the answer to. • A solution is a formula or series of steps required to convert raw data into the answer. • A program is the translation of the formula or solution steps into a programming language like Java. • A computation is executing the program with specific inputs to produce the answer to the original

problem. What kinds of problems can we solve with programming?

• simple formulas from algebra, geometry, trigonometry, calculus • generic statistics (mean, median, min, max, standard deviation, etc.) • medical statistics (clinical trials, drug effectiveness) • social policy statistics (median US income by zip code) • sports statistics (baseball ERA, basketball triple-doubles, soccer goals, shots on goal) • linear algebra (matrices and vectors) • financial calculations (mortgage payment, loan payment, loan qualifications) • date and calendar calculations (leap year calculations, etc.) • scientific/numeric calculations (physics, chemistry, engineering) • games and random number generation (maze builder/solver) • guess the number, craps (slightly more complex), pari-mutuel payout (quite a bit more complex) • modeling and simulations (weather and economic forecasts)

How does a program use the computer hardware to compute the solution to a problem?

• input the “raw” data • storage data held in main memory (RAM) • computation the formula or relationship to convert between inputs and results • output making the result available on the display or other output device

Example Problem Convert a temperature in degrees Fahrenheit into degrees Celsius Computation or Formula: by checking a reference manual, we can easily determine that the mathematical equation that captures the solution to the problem is X = (Y – 32) * (5/9) where Y is a temperature in °F (degrees Fahrenheit) X is a temperature in °C (degrees Celsius) Input: Y, which can be any number that you wish Output: X, the answer or solution, which is computed once the value of the input, X, is known. Any problem to be solved via computer programming must first be analyzed and placed into this form. You will not be able to convert your problem solution into a correct program without clearly identifying these elements of the solution first.

Page 3: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 3 Note Set #1

Algorithms and Problem Solving via Computer Programming In this course, you will learn how to do the following • Find a problem, usually stated in English (like a “word problem” in algebra), study it, understand it. • Find or create an algorithm (a recipe) that spells out how to solve the problem. • Translate the algorithm into a computer program (using Java in this course, but any programming language

could be used). • Use standard software tools (text editor, compiler, interpreter) to run the program, testing it to ensure that it is

correct, and finally executing the program on a computer to obtain the solution to the problem. You will use existing mathematical knowledge to help you be logical, accurate, and precise as you go through these steps. • (1) Develop a general way of thinking about problems and finding solutions. • (2) Master the details of the programming language (ie, Java). • (3) Improve your professionalism by correctly and reliably managing your files • (4) Learn how to use a text editor, compiler, and interpreter to develop and test programs in Java. What is a Problem? A problem is a question that somebody wants to know the answer to. A problem is more general than a single question, though. A problem is a way of describing a bunch of related questions all at once. A solution to the problem is the answer (or an answer) to the question. But there is an important distinction between phrasing the question and answer in a specific way or a general way. Specific Question: what is the area of square with a side of length 3 inches? Specific Answer: 3in * 3in = 9 in2 General Question: what is the area of a square with a side of length x? General Answer: area = x2 Specific Question: what is the monthly mortgage payment for a $200,000 loan, borrowed for 30 years at fixed interest rate of 5.5%, compounded monthly? Specific Answer: payment = $1135 General Question: what is the monthly mortgage payment for a loan of p dollars, borrowed for t years at fixed interest rate of r, compounded monthly? General Answer:

• Let mr = r/12 • Let mt = t*12 • Then payment =

�∙��

�� �(���)��

= �∙��

��(����)���

When solving problems in computer science with the goal of writing a computer program, we are usually only interested in general solutions. A specific question/answer can usually be transformed into a general question/answer by the correct use of symbols or variables. A computer program is usually written with a general solution in mind. When the program is executed, it becomes a specific solution when specific input values are input or plugged in. The execution ends with a specific answer based on those specific inputs.

Page 4: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 4 Note Set #1

Solving the Problem: Find (or Derive) a Formula Once you’ve identified the problem, you must now find a solution: given the inputs, what steps or operations must be performed to produce the answer. The solution is the path of steps that get you from the inputs to the answer. Solutions to many simple problems can be expressed as a formula . As a programmer, you either remember the formula, or do a little research and look it up when needed. Other problems that you will encounter may have no known formula that solves them. The programmer will have to try and derive the solution using their knowledge of math or other topics. Applying the Formula to Get a Result Formulas are a general solution to a problem because they use symbolic not specific values. Once you have specific values in mind, you plug the values into the formula and simplify it to get the specific solution. This is called applying the formula to the inputs to get the output or result. It is also known as “plug and grind”: plug the inputs into the formula and grind your way through the operations to get the final specific answer. If the formula is simple and there is not too much data, you can apply the formula to your data using pencil and paper (no computer or calculator required). If the formula is complicated and/or there is a large amount of data, you will more likely translate your formula into a computer program, enter the program and data into the computer, and let the computer determine the answer. Note that the programmer is responsible for “solving” the problem, not the computer. Computers don’t automatically figure out what to do with any data that you give it. The intellectual work of thinking about the problem, determining the general formula that solves it, and translating that formula into a program that the computer can execute, are all the programmer’s responsibility. The computer’s contribution is to accurately and quickly execute the steps or commands to get the specific solution.

Page 5: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 5 Note Set #1

Algorithm What is an algorithm? • A clear series of steps that describe how to find a solution to a problem based on initial values. • A highly technical and precise “recipe” for solving a problem. • All algorithms should be correct and complete and unambiguous. • Beyond this, good algorithms are general and symbolic. • Other qualities will be introduced over time From http://mathworld.wolfram.com/Algorithm.html:

A specific set of instructions for carrying out a procedure or solving a problem, usually with the requirement that the procedure terminate at some point. Specific algorithms sometimes also go by the name method, procedure, or technique. The word "algorithm" is a distortion of al-Khwarizmi, a Persian mathematician who wrote an influential treatise about algebraic methods. The process of applying an algorithm to an input to obtain an output is called a computation.

What does an algorithm look like? • Can be written in English (if care is taken to be precise) • Can be drawn as a diagram (flowchart) with steps and a path to follow between steps. • To make it precise (and executable), often translated into a computer language like Java. Example: give an algorithm in English to calculate the average of a list of numbers. • Let the number of numbers in the list be n. • Assume n is >= 1. • Calculate the sum of the n numbers. • Call this sum s. • Then the average is given by s/n. Example: give an algorithm to determine if roots of quadratic (2nd order) polynomial with real coefficients are real. • Careful statement of the problem

• Let the polynomial be expressed as ax2 + bx + c, and assume a, b, and c are all real. • The roots are defined as the solutions to the equation ax2 + bx + c = 0. • In other words, find the values of x that make the equation true. • From high school algebra we remember that the roots are given by the quadratic formula:

• ��,� = ��±�������

��

• If the radical √�� − 4 !is positive, there are two distinct real roots • If the radical is zero, there is one repeated real root. • If the radical is negative, there are two distinct complex roots

• Solution

• Using the subexpression under the radical in the quadratic formula, evaluate b2 – 4ac • If b2 – 4ac is positive or zero (nonnegative), then the roots of the polynomial are real. • Otherwise, the roots are complex.

Make steps of algorithm clear and unambiguous A good algorithm should be “bulletproof”. It should be easy for someone trying to follow the instructions to do it correctly and not make a mistake because the steps were hard to understand. If you give the same instructions to 100 people, each person will arrive at the same answer. The person following the instructions should not even need to know the purpose of the steps, if they follow the steps, they will get the answer. Make algorithms general by using symbols Useful algorithms are reasonably general. They give the right answer for a wide range of inputs. How is generality introduced into the algorithm? By using symbols or variables to represent general values rather than specific values – n, s, a, b, c, etc. rather than 3.5, 7.2, etc.

Page 6: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 6 Note Set #1

Many common algorithms are based on mathematical formulas A formula or equation is one kind of very simple algorithm. This is very typical of many mathematical problems that have a closed-form solution. Not all interesting problems have such clean or simple solutions. Most problems have more than one algorithm, so pick the “best” one For many problems, there may be more than one way to solve it. That is, for some problem, there may be multiple algorithms that solve it. In this case you should pick the “best” one. But what makes one algorithm better than another? Generally, we pick the algorithm that gets to the solution the fastest, but other definitions of “best” are possible. Algorithms for walking 3 feet to the right Algorithm #1 • turn left and walk 10 feet • turn left and walk 5 feet • turn left and walk 13 feet • turn left and walk 5 feet • done Algorithm #2 • turn right and walk 3 feet • done In the absence of any other information, #1 seems inefficient, and #2 seems obvious and fast. But if you’re standing by a wall, the only way to reach your destination might be to walk around the wall. It’s good that there are multiple ways to solve a given problem. But always pick the most simple and obvious solution unless you have a good reason to prefer a more complicated solution. Exercise Given three distinct integers, describe how to arrange the integers in ascending order (this is a simple version of the sorting problem). Exercise Given 10 integers, describe how to find out if a specific value matches any one of the 10 integers (this is called the search or lookup problem). Exercise Find the GCD (greatest common divisor) of 30 and 252. • Use symbols x, y, and z rather than specific numerical values. • For all symbols, indicate clearly if they are inputs, temporaries, or outputs (results). • Your steps should work for any two numbers x and y (not just 30 and 252). It should be general. • Your steps should be so clear that even someone unfamiliar with the concept of GCD can solve it. It should be

clear, precise, and unambiguous. This description (which does not depend on any specific numbers a and b) is called an algorithm. The algorithm by itself doesn’t produce a specific answer. The algorithm must be applied to specific numbers to generate a specific answer. This is called a computation.

Page 7: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 7 Note Set #1

How to “execute” or follow the steps of the algorithm: Get a pencil and paper ... A bright, industrious human, with a pad of paper and a pencil, should be able to take an algorithm, apply it to some data, then follow the steps until a solution is found. So, a good algorithm should be stated clearly enough for a human to follow the steps manually. Alternative: Get a machine to do it for you ... But interesting problems require a large number of steps to be followed, so manual execution isn’t practical. We need to automate the execution of the steps in the algorithm. We must present the algorithm and the data to a machine (usually a digital computer) to execute the steps in the algorithm in an automated way. Important point: whether a human or a computer executes the steps, the answer should be the same. A computer cannot perform magic, it can only follow the instructions that it is given. Computers are, however, faster and more accurate than most humans. Important point: If you don’t understand a problem well enough to clearly describe how to solve it to a human, you’ll never be able to explain it to a computer. But how to get a machine to follow your instructions ... This is what programming is all about. Consider this scenario: Your boss gives you a problem and says “I need the answer in 3 hours”. Step One: figure out if the problem has a solution [computable vs. non-computable problems] If it doesn’t, figure out a way to gently explain this to your boss. If it does, you have to find one. It is not enough to say “Great! There is a solution! I’m Done!” You must actually use the solution to get the answer, and make sure the answer is correct. Step Two: pick an algorithm (or create your own) Now do a little planning: can you follow the steps of the algorithm using pencil and paper? For a small amout of data, sure! For a massive amount of data, probably not! And this problem is massive, so ...

[Steps One and Two are called problem solving.] Step Three: Using a programming language (C or C++ or C# or Java or Pascal or ...), translate the algorithm into a program.

[Step Three is called programming (some authors would including steps 4-6).] Step Four: Using available computer applications designed for that language (usually called compilers), translate the program into an executable application. Step Five: Execute the application, giving it your input data, and wait for it to print out the results (the answer). Step Six: Using your own common sense and technical insight, study the answer to convince yourself that it is reasonable and correct. Observation: out of the entire process required to get the job done (obtain the answer to the problem that your boss gave you), notice how much of the process involved programming.

Page 8: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 8 Note Set #1

The Role of Programming Languages Like Java Once a programmer has solved a problem and picked an algorithm, he often wants the computer to now execute the algorithm to obtain the answer. Computer systems are built around a special chip called the CPU (central processing unit), and the only instructions or operations that computer can directly follow are the instructions that are designed into the CPU, called machine language instructions. To a human eye, these instructions appear to be a meaningless series of 0s and 1s, but to the CPU, each pattern has a special meaning. Most programmers aren’t fluent in commanding the computer using machine language, so a more efficient way to give commands to the computer is to write commands defined by a higher-level language (HLL) or programming language like Java. We use a text editor to write a Java program (called source and stored in a .java file). The source code is then translated into machine language by an automatic translator called a compiler. In the case of Java, the compiler produces instructions in a form similar to machine language called bytecodes and stored in a .class file). Finally, after compilation, the bytecodes can be executed on the computer by another program called an interpreter . Computer programs are not written with no context. Take the example of an English essay. An essay is not just a random collection of sentences, but is written in an organized way to make a point. In the same way, a program is written in an organized way in order to solve a problem and get a result. Types of Computer Hardware A computer is an electronic device (the hardware) with components specifically for • storage (memory cells where data and instructions can be stored) • computation (special processor chip that can perform arithmetic, comparisons, etc.) • input device (keyboard) • output device (monitor) [More detail on this in COMP 122 and 222]. Given these hardware components, what kind of operations can the computer perform? Computer instructions can • perform arithmetic (add sub mul div etc) • perform comparisons and logical (Boolean) operations (and or not less-than greater-than etc); “Boolean” is an

adjective named for English mathematician George Boole (1815-1864). • give names to cells in memory (define variables) • store values into named cells (assignment) [a cell is a single storage location in primary memory] • read values from named cells • capture input entered by the user (usually from the keyboard) (input) • produce output to indicate the result of computations (usually to the monitor) (output)

[collectively, input and output are abbreviated I/O] • execute a series of instructions grouped together to form a program • make decisions based on the result of comparisons (branches) • repeat the execution of a subset of the instructions for as many times as necessary (loops) • give a name to a subset of the instructions in a program and execute them as a group or block (subprograms,

subroutines, functions, methods) [learning how to express these operations in Java covers about half the course]

Page 9: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 9 Note Set #1

What are the steps in creating an application and entering it into the computer for execution? Stage 1: Writing the Program To create a program, the programmer uses a text editor and enters the desired statements into a file and saves it to the computer’s secondary storage (ie hard disk). It is the task of the programmer to figure out a way to describe the solution in terms of the basic steps that the computer can actually follow. The computer is great at following instructions quickly, accurately, and tirelessly. But it has no inherent ability to determine which instructions are needed to solve a problem. The programmer solves the problem by writing a program. The computer is only following instructions as described by the programmer. Stage 2: Executing the Program The statements are then processed and submitted to the computer for execution. Once the computer begins to execute the program, any required inputs are entered from the keyboard. The computer then performs the computation as described by the program, until it reaches the last statement. Near the end of the program, the result or answer has been computed, and it is output to the monitor, and the program terminates. Important Point: If the user of the program finds a problem, the programmer must fix the problem and “rebuild” the software application, send it to the user, have the user remove the old software and install the corrected software, etc. Therefore, the programmer must ensure that the program is correct (and general) before releasing it to the user.

Page 10: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 10 Note Set #1

Outline of a generic (and simple) computer application • application advances by instructions that

o obtain input o perform computation (storage, arithmetic, Boolean logic) o produce output

• program advances in time, one instruction after another, like clicks on a crank • effect of program is very deterministic, not random flipping of bits

Reason for emphasizing problem solving rather than a specific language. Problem solving is a general skill that is not specific to any language. Languages come and go, but problem solving skill is general. Previously, Computer Science departments taught programming based on Pascal or C. Today, Java and C++ are popular. Ten years from now, some other language will be popular. No matter which language is being taught, mathematics, logic, basic problem solving skills will still be in use. Currently, Java has been chosen as the best of what’s available. The focus of the course is not teaching the details of the Java language, although you will have to learn them in order to complete lab assignments. Much of the material presented here regarding how to solve problems is not specific to the Java language. Once you’ve thought about how to solve a problem, you have a “design” in mind, an overall approach of how to choose instructions or statements to compute an answer. This design must be expressed in some HLL (high level language), and you’ll be using Java in this class. But a good design can actually be translated into an HLL. Most experienced programmers feel that the “hard” part of programming is coming up with the design. Translating the design into a program is the “easy” part. A language is just a tool. A language that is hot and popular today may be dead and gone 10 years from now, and another new hot language will have replaced it. So avoid language chauvinism: “I don’t like C++ and I don’t like people who do!” Problem solving and program design skills are fundamental and long lasting. As a professional programmer, you will learn and use many different languages, so don’t get too attached to one.

Computer ApplicationInput (raw data)

Output (processed data,results)

Computer ApplicationInput (raw data)

Output (processed data,results)

Page 11: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 11 Note Set #1

Another Characteristic of Good Programs: Clarity and Unambiguousness. In professional software development, one of the early stages is called requirements capture. Before any software can be produced, there must be a clear statement of what the software should do. A requirement is a statement in English that states something about how the software to be developed should work. For a large software project, requirements capture is a major phase of the development. Requirements must be worked out and documented by professionals with expertise in the area. A big problem with writing good requirements is to avoid ambiguity. This means that the requirements must be written in such a way that they cannot be misinterpreted or interpreted in different ways by different readers. Many infamous and expensive software project failures can be traced back to ambiguous or incomplete requirements. The following ambiguous requirements are taken from the a paper that studies the consequences of requirements mistakes:

• The customer enters a card and a numeric personal code. If it is not valid then the ATM rejects the card. • For up to 12 aircraft, the small display format shall be used. Otherwise, the large display format shall be

used. • When the user presses the L- and R-button simultaneously, the alarm is turned off.

Taken from http://prof.kamsties.com/download/icssea2000.pdf. Ambiguity Example from Natural Language (English)

• The President told the crowd he was glad to be in Cleveland, and then the First Lady told a joke. • The President told the crowd he was glad to be in Cleveland, and then the First Lady told a joke.

In speech, the ambiguity is resolved by using vocal stress to clarify meaning (see bold text). Ambiguity Example from SNL In a Saturday Night Live episode, the manager of a nuclear power plant was about to leave for vacation. The remaining staff asked when water should be added. The manager smiled, said “oh, you can never add too much water to the reactor,” and left on vacation, leaving the team to wonder about the difference between “can never” and “must never.” Another Characteristic of Good Programs: Termination Instructions commonly written on a bottle of shampoo: rinse lather repeat. Common sense suggests that the “repeat” instruction should only be followed once. But computers follow instructions literally, so this is not a good algorithm because it doesn’t terminate. Such a program flaw is called an “infinite loop.” A good algorithm must reach a stopping point after a finite amount of time.

Page 12: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 12 Note Set #1

Noteset #1 Part II (The Nuts and Bolts) Intro To Java A Simple Program Written in Java (Output Only) Several steps are required to get a program into primary memory and ready for execution. First, instructions are typed into a file and saved to secondary storage (disk). Instructions can be based on any of several programming languages, but in this course, we will be using the Java programming language and writing Java programs. A Java program is a series of instructions written according to the rules of the Java language and stored in a file with filename extension “.java”. This file can be created with any text editor (eg, Notepad on Windows, emacs on Unix). A popular editor available on lab computers is GWD, but you are free to use any editor you want. Here’s an example of a simple Java program: public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello, world!”); } } Although there are many technical elements of this program that you don’t need to understand yet, here’s a description of what this program means. Class Definitions Java programs are defined in units called class definitions. A programmer defines as many classes as needed to solve the problem of interest. Each class is given a name “invented” by the programmer. This program is a definition of a class named “HelloWorld”. The words “public” and “class” are examples of Java keywords, ie, words that are predefined by the Java language. The opening and closing curly brackets “{” and “}” are important for indicating how instructions are grouped together in a program. So an abbreviated version of our class definition is class HelloWorld { ... } where the ... indicates the content of the class definition. Java, like other languages, uses lots of “punctuation” and “grouping” characters to indicate structure.

( and ) parentheses { and } curly brackets [ and ] square brackets “ and ” double quotes ‘ and ’ single quotes

These various grouping symbols each have a specific use. They are not interchangeable. You will have to learn exactly when to use one set or when to use another.

Page 13: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 13 Note Set #1

Method Definitions What can we put inside a Java class definition? A Java class definition can contain multiple blocks of instructions called methods. In our simple example, the HelloWorld class definition contains a single method named “main”. As with the class definition, the words “public static void” are Java keywords that must be added as shown (the “why” will be presented later). The name of a method is always followed by a set of parenthesis, which may or may not be empty. The info inside the parentheses defines the method’s parameters, or information that the method needs when it is executed. As with the class definition itself, the method also uses curly brackets to define its starting and stopping point. An abbreviated version of our method definition is main( ... ) { ... } Since the method definition is inside the class definition, we can summarize the program like this class HelloWorld { main( ... ) { ... } } The important words like “class” and “main”, plus the punctuation characters “()” and “{}” create a structure that must be organized correctly in order for your program to be recognized by the computer as a correct Java program. You must pay attention to this arrangement and get it right , otherwise you will waste a lot of time editing your work and trying to correct it. It’s much faster to write your definitions correctly the first time. And there are many more wrong ways to write a program than correct ways: Wrong: main( ) { } class HelloWorld { } (main method is outside the class) Wrong: class HelloWorld ( main{} ( ) ) (use of parens and brackets is reversed) Wrong: class HelloWorld{ () main { } } (parens come after main) Wrong: class HelloWorld { main() } { } (brackets not nested correctly) ... Note that no matter what line opening and closing parens or brackets are placed on, you must learn to recognize the corresponding opening and closing elements of a pair when visually looking over your program. For example, in this case:

class HelloWorld { main(...) { ... } } 1 2 3 4 5 6 you must quickly learn to recognize at a glance that positions 1 and 6 match, positions 2 and 3 match, and positions 4 and 5 match. In general the positions will not be numbered and you will have to infer that this matching is correct. When pairs of brackets appear inside other pairs, there is only one way that they can be made to match. This arrangement is called nesting. For example { { } } 1 2 3 4 In this example, positions 1 and 4 match, and positions 2 and 3 match. It is not allowed for 1 and 3 to match, and 2 and 4 to match. This is because such pairs are not nested. Nesting means that one matching pair is completely inside or within another matching pair. Correctly recognizing matching pairs of grouping characters is not a trivial exercise. You will not be able to read or write correct programs if you cannot correctly match the pairs.

Page 14: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 14 Note Set #1

Statements Now let’s go one level further. What can we put inside a method? A Java method contains a set of instructions called statements that give the method its meaning. The main method for this program contains a single statement: System.out.println("Hello, world!"); This is the basic Java output statement, ie, an instruction or command to the computer that causes info to be printed onto the display when the program is executed. Let’s break this statement down into its pieces. The part of this statement that is predefined and therefore fixed is System.out.println( ... ); When describing this statement verbally, we might say “system dot out dot print line”. Note that the “ln” in “println” is “ell” + “en”, not “one” + “en”. And once again, please pay close attention to the difference between upper and lower case, it must be written exactly as shown. This statement is used over and over in just about any Java program to send information to the monitor screen. The information to be sent always appears inside the parentheses. In this case, the information being sent is "Hello, world!" String constant (String is a kind of data, or data type) This is an example of a particular kind of Java information called a String constant. A String constant is any series of text characters surrounded by double quotes. You cannot use single quotes as a substitute for double quotes. Single quotes are reserved for a different purpose. At the end of the statement, note the semicolon “;”. A semicolon is used in Java as a statement terminator, much like a period “.” is used as a sentence terminator in English (and other languages). Also pay attention to the difference between plain double quotes (") and so-called smart quotes used by word processing applications like MS Word (“ and ”). Java programs must only contain plain double and plain single quotes. Smart quotes are illegal characters and will not be recognized. Most program editors will use plain quotes. But you may discover this problem if you write code in MS Word then copy and paste it into a Java source code file. Bottom line: MS Word is not a good choice of application for composing Java programs. Some statements will spill across multiple lines. In these cases it is important not to put a semicolon at the end of every line, only at the end of the entire statement. For example, here is a more complex multi-line statement: for (int i=1; i<10; i++) x = x + i; It would also be okay to write this statement on one line: for (int i=1; i<10; i++) x = x + i; But it’s very common to spread complex statements across multiple lines to aid its readability. In this case, you must not add extra semicolons: Wrong: for (int i=1; i<10; i++); x = x + i; This statement has now been broken into two statements, and changing its meaning. In fact, it will no longer compile, which means that it contains logic errors that prevent it from being translated into a working program.

Page 15: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 15 Note Set #1

Java Programs with Input In this part of the lab, you will add statements to your program to allow it to obtain input from the keyboard. The statements should initially be treated as formulas that must be used as-is. Don’t worry about fully understanding what the formulas mean yet. They will be explained in detail later in the course, but the most immediate goal is that you start using them in your programs right away. Types of Data in Java: Strings and Numbers As with many programming languages, data that represents text is stored and manipulated differently from data that represents numbers. In Java, any info appearing in your program that is inside matching pairs of double quotes is called a String. The string represents a piece of textual data and is made up of individual characters. Some examples of Strings are

"hello" "another string with spaces, and punctuation!" "a string containing numerical digits: 123"

Double quotation marks must be used to define a String. You cannot substitute single quotes, because these are reserved for a different purpose. Combining Strings with the Append Operator The first operation that we’ll learn about for Strings is that Strings in Java can be “glued together” or appended using the append operator “+” (same as the “plus” sign for numerical addition). The two statements

System.out.println("Hello, world!"); System.out.println("Hello, " + "world!");

perform the same operation. The same effect can be achieved with the two statements

System.out.print("Hello, "); System.out.println("world");

Note that the first statement uses the “print” operation, not the “println” operation, so no newline is added at the end of the first output operation. The result of the second output operation is just added to the end of the first on the same line of the output.

Page 16: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 16 Note Set #1

Textual Information on the Computer All information on the computer is stored in a binary numerical form. But there is a need to manipulate textual as well as numerical information. Not all problems to be solved by computer are numerical. For example: given an electronic phone book, list the names in alphabetical order. So how do we get text into the computer if it actually only supports numbers? Text is represented on the computer by using a little trick called encoding. An encoding is a table that assigns a numerical value for each character. That is, whenever the computer user presses a character on the keyboard (letters, digits, punctuation, etc.) a numerical code defined by the encoding is substituted and entered into computer memory in the place of the actual character. The most common encoding used in computers for representing characters is called the ASCII code (American Standard Code for Information Interchange). Here are a few of the codes (many versions of the table exist in reference books and web pages): 'A' 65 'B' 66 'C' 67 ... 'a' 97 'b' 98 'c' 99 ... Since these are kind of hard to remember, the Java language provides a shortcut to refer to individual characters: the character itself enclosed in single quotes. • 'a' • 'b' • 'c' • 'A' • ':' • '!' Recall that String constants are series of characters inside double quotes • "this is a string" • "Hello, world!" • "x" (a String containing the single character x) • 'x' (the character constant for the character x) Wrong: 'this means nothing' (neither a valid Strin g nor

character constant) A String constant is just a series of character constants that have been linked together as a unit. These last two examples are not identical.

Page 17: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 17 Note Set #1

String Append An important operation for text is to be able to glue together multiple small strings into a single larger string. Java allows many flexible expressions for creating strings from subparts of different types. The main operation to glue strings together is the append operation, represented by the plus sign: +. This is an example of Java feature called operator overloading. The + sign can mean either arithmetic addition or string append depending on context. Here are some examples of using the append operator with strings. System.out.println("abcdefghijklmnopqrstuvwxyzABCDE FG"); is equivalent to System.out.println("abcdefg" + "hijklmnop" + "qrstu vwxyzABCDEFG"); is equivalent to System.out.println(

"abcdefg" + "hijklmnop" + "qrstuvwxyzABCDEFG"

); A useful trick illustrated by these examples is to break up an overly long string into multiple substrings connected by append operators. Some common style guidelines for writing Java source code are avoiding line break problems from overly long lines, and to use indentation and white space (newlines, spaces, and tabs) to align related lines of code to increase readability. Strings can also be appended from data of different types, with some restrictions. Here are some examples "abcde" + 'f' + "ghij" + 'k' is equivalent to "abcdefghijk" In this example, string constants and character constants have been mixed together and appended. Numbers can be combined with text as well. "abcde" + 123 + "fgh" is equivalent to "abcde123fgh" Technically, when a number is appended to a string, the number is first converted to a string and then appended. This feature is useful when trying to combine a fixed string with the numerical value of a variable:

int total = 325; System.out.println("The value is " + total + ".");

This code will print The value is 325. to the display. The value of the named variable (325) is converted to a string ("325") and appended with the other strings, then output to the display.

Page 18: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 18 Note Set #1

Data types (continued) Numbers are a different type of data to be manipulated by Java programs. It might not seem like an important distinction, but like most programming languages, Java requires the programmer to make a distinction between numbers with and without a fractional part . A number without a fractional part is called a whole number or integer in mathematics. Java uses the special abbreviation int for this kind of data. A number with a fractional part is called a real number in mathematics. Java uses the special abbreviation double. In the history of computers, it has always been the case that arithmetic on integers is “easier” than arithmetic on real numbers. The distinction might not be as important as it used to be, but it is firmly established and most programming languages will require you to make a distinction. Integer constants Java has a few rules about how you can write numbers inside a Java program • -15 • -1 • 0 • 1 • 45 • 1234 (no comma separators) • 123456789 • -54321 Wrong: 12,345 (comma breaks number into two parts) Real (double) constants • 3.14159 • -0.000025 (can also be written –2.5e–5) • 0.00025 (can also be written 2.5e–4) • 54321.98 (can also be written 5.432198e4) Real constants can be written in “scientific notation” as shown. The expression "ex" represents the value 10x, where x can be positive or negative. So -2.5e-5 represents -2.5 * 10 -5 . Operations on Numbers: Arithmetic The standard operations + - * / are used in Java with mostly the same meaning as in algebra. 5 + 3 22 – 4 15 / 4 19 * 143 The operations have the same precedence as they do in algebra. 5 + 3 * 2 value is 11 To change precedence, use parentheses. (5 + 3) * 2 value is 16

Page 19: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 19 Note Set #1

There are a few instances where the results of using these operations may give a surprising result. For example, division is evaluated differently depending on whether the operands are int or double.

4.0 / 2.0 result is 2.0 5.0 / 2.0 result is 2.5 4/2 result is 2 5/2 result is still 2, because remainder is discarded

The result of integer arithmetic is always an integer, even in the presence of division. If either or both operand is a double, the result is a double. Note that this is an example of a rule of the Java language. You cannot blindly use your mathematical intuition to figure out all such Java rules, they must be memorized. Programming language features have been inspired by mathematics, but the Java language is its own authority for the syntax and sematics of Java code expressions. Math is math, and Java is Java. Integer division discards the remainder, and only preserves the quotient. What if you really want to keep the remainder? There is another arithmetic operation % called the modulo operation, that does just that: 4 % 2: result is 0 (the remainder after dividing 4 by 2 is 0) (read “4 modulo 2”) 5 % 2: result is 1 (the remainder after dividing 5 by 2 is 1) (read “5 modulo 2”) 7 % 3: result is 1 8 % 3: result is 2 9 % 3: result is 0 99 % 100: result is 99 ... There is no built-in operation for exponentiation. Some languages use ^, but this is not supported in Java. Instead, you must use the Math.pow() function or method: double x = 2.3; double y = 3; double z = Math.pow(x,y); // z = x y Formal Java Datatypes We’ve been talking about the different types of data informally, but when writing a program, we actually have to be precise about what kind of data is being used. In other words, we have to explicitly refer to a data item’s data type. There are many different data types in Java, but for now we will focus on the following 3 types: int for integer numbers double for real numbers String for Strings of text Variables for Holding Strings and Numbers Java gives the programmer access to the storage provided by the computer hardware. Inside a Java program, a special statement called a variable declaration creates or reserves a block of space in memory, called a variable, for the use of the program.

Page 20: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 20 Note Set #1

Just like a memory register in a hand-held calculator, a variable is a space in memory where a value can be temporarily stored. To declare or create a variable, the programmer must indicate what type of value will be stored in the variable (int, double, or String), and the programmer must invent a name to identify the variable by. Here are some examples of variable declarations. String s; means “create a variable named s to hold String data” int x; means “create a variable named x to hold int data” double y; means “create a variable named y to hold a double value” Declaring a variable is a command to the computer. The computer responds to this command by creating and naming some storage location within the main memory (RAM). You must learn the meaning of this command and be able to read and understand it in other people’s programs, and write it correctly in your own programs. Notice that there is no appearance of the words declare or create variable. You just have to learn what the statement means as shown. Also, creating a variable is a totally separate operation from giving the variable a value. Immediately after its creation, a variable is just an empty box in memory with no defined value or contents. It doesn’t acquire a value until a specific value is placed in the variable.

Page 21: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 21 Note Set #1

Storing Values into Variables: The Assignment Operator = One of the most important (and frequent) operations that comes up in a typical program is computing some value and then storing it away for safekeeping in some variable. This is totally analogous to storing a value into a register in a handheld calculator. The operation of placing a value into a variable is called an assignment operation. We assign values to variables. The symbol used to indicate assignment is the equals sign “=”. Here’s an example: int count; variable declaration statement: create a var named count and datatype int count = 0; assignment statement: assign the value 0 to the variable count Assignment is often misunderstood by beginning programmers. The problem is the unfortunate use of the “=” symbol. To a beginning programmer, this symbol looks like a comparison in algebra. But Java and algebra use the same symbol for different purposes. You must remember that when the symbol “=” is encountered in a Java program, it means an assignment is taking place. It has nothing to do with algebraic comparison. Assignment has some very sensible restrictions on how it can be written, although they make look a little funny at first. For example, the left hand side (LHS) of the assignment operator “=” must be the name of a declared variable. int x; x = 15; // correct 15 = x; // incorrect, assignments flow from R to L Here’s a very clear example of how different assignment is from algebraic equality. The LHS and RHS are not interchangeable. Left to right order is significant. The LHS indicates the name of the variable whose value is being changed, the RHS indicates the value being stored. As an aside, note that variables cannot appear in any expression until they have first been properly declared. count = 0; // wrong, count not declared first. int count; count = 0; // correct, declared first, then initi alized. int count = 0; // correct, declared and init in on e statement. Here’s yet another example of how assignment is different from algebra: int x = 0; x = x + 1; As an algebraic equality,

x = x + 1; is an equation without a solution (there is no value of x for which x = x +1). But in the context of a Java program, this is an assignment statement, not an assertion of algebraic equality. The statement says, reading from right to left:

• Take the current value of x • Use the addition operation + to add one to that value • Use the assignment operation = to make this value the new value of x

In other words, increase the current value of x (whatever it happens to be) by 1.

Page 22: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 22 Note Set #1

int x = 0; x currently has value 0 x = x + 1; after this statement executes, x will h ave value 1 x = x + 1; after this statement executes, x will h ave value 2 ... and so on Note that in this example, another important fact about programs is introduced: instructions are executed sequentially in time. If instruction #1 assigns a value of 10 to variable x, then instruction #2 adds 1 to whatever in x, then instruction #3 reads the value of x, what value will it find in x? Reading a program and then using pencil and paper to try and keep track of what the program is doing is a very useful exercise called program tracing, and we will do this a lot in this course later on. Converting Strings into Numbers Look carefully at the two data items: 123 "123" Although they seem similar enough, Java treats them very differently. The first is a number, specifically, an integer. The second is a String. To Java, the fact that the String contains characters that represent digits is not important, the data item is still a String. Recalling what was explained about characters and encoding, here’s a more detailed picture of how the number 123 and the String “123” are stored in memory. The number 123 is stored directly in a cell somewhere in memory

123 The String "123" is stored as a series of three character codes:

31 32 33 where the character code for the digit ‘1’ is 31, the code for ‘2’ is 32, and the code for ‘3’ is 33. Seen in this way, it should be clearer that Strings and numbers are different. Even though a String may look like a number, it must be converted before it’s numerical value is available for calculations. The conversion process that converts a String to an equivalent numerical value is called parsing. That is, we parse the String to find out its numerical value. String w = "123"; assign "123" to variable w int y = Integer.parseInt(w); parse "123" to obtain 123,

assign it to variable y String v = "3.45"; double z = Double.parseDouble(v); Java provides more than one statement to perform parsing. Obviously, not all Strings can be parsed into a number (e.g., " cat", " dog" or any String that contains non-digit characters). If you try to parse a String that is not actually parseable, the program generates an exception (a kind of error) and the program terminates. Exceptions will be covered much later in the course.

Page 23: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 23 Note Set #1

Obtaining Input from the Keyboard: the Scanner In order to prepare any Java program for receiving input, several statements must be added to the program. These statements create a program element called a Scanner. The Scanner is a predefined program element that is provided by the Java program development tools that have been installed on the lab computer. Although the statements that create the Scanner may be hard to understand at this point, you should just follow the directions as given. Detailed explanation will come later in the course. The statement that creates the Scanner looks like this:

// insert this line at top of file import java.util.*; // insert this line inside your “main” method Scanner in = new Scanner(System.in); This statement only has to be added to your program once, near the top of the main method. The Scanner must be given a name when it is created. In this example, the name chosen is “in”. Any name can be chosen, but “in” is a good choice since it reminds us of its purpose: input. The book uses “keyboard” instead of “in”, this is a good choice, too. Now that the Scanner has been created, it can be used as many times as needed to obtain inputs from the keyboard. Here are some examples: int x; double y; String s; x = in.nextInt(); // next integer y = in.nextDouble(); // next real number s = in.next(); // string surrounded by space These examples illustrate that the Scanner can be used to receive inputs of different datatypes from the keyboard. If the program is expecting an integer input, it uses the in.nextInt() command to obtain the value and the result is stored into an int variable, named x in the example. An alternative way to process input is to treat the entire line of input as a string, even if it appears contain a mixture of numbers, text, and spaces. String t; t = in.nextLine(); // string (entire line) This type of input processing is useful if the program is responsible for detecting errors in the input (wrong data type for example), but it is more complex, and we won’t be using it until later.

Page 24: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 24 Note Set #1

An Example Java Program that Requires Input In this program, the user is asked to enter their name, which will be treated as a pure text String that doesn’t require further processing. After the name is entered, a personalized version of the “hello” greeting from the previous program is output to the display. import java.util.*; public class PersonalHello { public static void main(String[] args) {

Scanner in = new Scanner(System.in); String nm; System.out.print(“Hi, please enter your name: ”) ; nm = in.next();

System.out.println(“Hello, ” + nm + “, welcome to Java programming!”);

} } The “import” statement at the top The Scanner object represents an element of software that has been provided by the Java development environment, and can be easily added to your program. But to use it, you must add an “import” statement near the top of your program to explain what predefined software package contains its definition. In this case, we can infer that Scanner is defined in the “java.util” (the java utility) package. Every experienced Java programmer will have to learn about which program elements are defined in which package, but you don’t have to worry about those details yet.

Page 25: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 25 Note Set #1

Another Example Program that Requires Input Here is a slightly more complex program that asks the user to enter two integers. The integers are received in the form of Strings, which must be parsed to obtain the equivalent numerical value. Once the numbers are obtained, they are added together, and the sum is printed to the display. import java.util.*;

public class DoAdd {

public static void main(String[] args) { Scanner in = new Scanner(System.in); String str1; String str2; int num1; int num2; int result; System.out.print("Please enter the first integer: "); str1 = in.nextLine(); System.out.print("Please enter the second integer: "); str2 = in.nextLine(); num1 = Integer.parseInt(str1); num2 = Integer.parseInt(str2); result = num1 + num2; System.out.println("The sum of the two integers is " +

result); }

} In this example, the input is read one line at a time in the form of Strings. The Strings need to be converted to numbers before they can be added to obtain the result. See the lab project as another approach to solving the same problem.

Page 26: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 26 Note Set #1

Program Development and the Java Development Tools: Text Editor, Compiler, Interpreter We’ve covered the basics of designing a simple Java program. Here, we describe the mechanical steps to “build” the executable application from the Java program that you write. The steps may seem tedious, but you will execute the same steps for every program you develop. After some practice, the steps will become part of your memorized skill set. Below is a summary of the steps. You will receive more detailed hands-on assistance with the steps during lab sessions. Note that these instructions assume you are using the programming tools from the command interface (called the command prompt on Windows platforms, and the terminal window on MacOS, Linux, and Unix platforms). These same steps can be performed inside the JGrasp application via menu items and command buttons. Create the program: using a text editor To start the Java program development process, you must open an editor session using a text editor, type the class definition described in Part 1, Background information, into a new document window, then save it to a file named “HelloWorld.java ”. Note that Java is case sensitive, even with respect to the name of the file containing your program. Also note that a class definition must be saved to a file with a matching name. Compile the program: using the Java Compiler: javac Once the Java program has been typed into the editor window and saved to a file on disk, we’re ready to advance to the next step. The file contains instructions written according to the rules of the Java language. But the computer hardware that will execute the instructions (the CPU) doesn’t understand Java directly. The CPU only understands instructions in a very specific binary form (0’s and 1’s). The Java program in the file must first be translated into the form of binary instructions that the hardware is expecting and can understand. This translation is called compilation, and the software application that performs the compilation is called the compiler. The program named javac is the Java compiler installed on the lab computers to perform this compilation or translation. The translation could theoretically be done manually, but would be very slow and tedious and error prone, so the Java compiler is the best way to go. From the command line prompt, the Java compiler is launched by typing its name followed by the name of the file that contains the Java program being compiled. For example, to compile the Java program above, type % javac HelloWorld.java If there are any typing mistakes in the file, the compiler will list a series of error messages on the screen. If there are any error messages, the messages must be read carefully to figure out what the problem with the file is. The programmer must go back to the editor, open the program file, make corrections, save the changes, and try to compile it again. This process must continue until the compiler reports no errors. Once the compilation completes successfully (i.e., no error messages), the compiler creates a new file which is the translated version of the original file. This new file is called a class file or bytecode file. It has the same name as the original file, but with a filename extension of “.class”. For example, after compiling the file “HelloWorld.java,” there will be 2 files on the disk: the original, and the translated file named “HelloWorld.class”. The compiler creates and names this file automatically, as a side effect of the user invoking the compiler command. Note that the class file contains instructions in a binary format. If you open it directly with a text editor and try to read it, its content looks like a mixture of 0s and 1s and snippets of text that can’t be easily understood.

Page 27: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 27 Note Set #1

Run the Program: using the Java Interpreter: java The Java compiler creates a file containing instructions to be executed, but it doesn’t actually execute them. The user must execute a second software application called the Java interpreter . The interpreter is named simply java. The interpreter reads the instructions in the class file and executes them. For example, to execute the HelloWorld program after compilation, return to the DOS prompt or terminal window and type the following:

% java HelloWorld Note that the interpreter is given the name of the class file with the filename extension omitted, ie, don’t type “java HelloWorld.class”. Once the program is executed, it simply sends its output to the display and terminates:

Hello, world! %

The reappearance of the prompt symbol “%” is your signal that the program has terminated. Complications The program development process as described above is the ideal simplified case. In real life, things go wrong at the different steps, and that step and even possibly all the previous steps have to be repeated many times before the program is correctly completed. This is potentially a very frustrating aspect of computer programming for some people. You have been warned!

Page 28: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 28 Note Set #1

Summary Diagram: Program Development Process

public class HelloWorld{ … }

Type this programinto a file named“HelloWorld.java”

javac HelloWorld.javaCompile it withthe “javac” Javacompiler

010110101 …This produces a bytecodefile named “HelloWorld.class”

java HelloWorld Run or execute the program withThe “java” interpreter

Hello, world!

Results are printed to the screen.

public class HelloWorld{ … }

Type this programinto a file named“HelloWorld.java”

javac HelloWorld.javaCompile it withthe “javac” Javacompiler

010110101 …This produces a bytecodefile named “HelloWorld.class”

java HelloWorld Run or execute the program withThe “java” interpreter

Hello, world!

Results are printed to the screen.

Page 29: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 29 Note Set #1

Part III Programming and the CS Major The Computer Science major focuses on software development starting with basic courses in programming and problem solving at the lower division, and specific application areas such as networking, security, and web at the upper division. COMP 110 is part of an introductory 3-semester sequence that focuses on problem solving and programming: • COMP 110 Algorithms and Problem Solving • COMP 182 Data Structures • COMP 282 Advanced Data Structures Example Topics Covered in COMP 110 • Computer Hardware Concepts: Input, Output, Storage, Computation • Representing Numerical and Textual Data on a Computer • Solving Problems involving Numerical and Textual Data • Arithmetic for Numerical Data and String Manipulation for Textual Data • Boolean Logic: Computation using True/False Values and Expressions • Decision Making: Branches or If-Else Logic • Repetition: Looping • Organizing Statements into Units: Methods (aka Functions) • Intro to Object-Oriented Programming (OOP) • Defining Structured Data Types with Class Definitions • Inheritance and Polymorphism • Intro to Computer Graphics and Graphical User Interfaces (GUIs) COMP 182 example topics Stacks, Queues, Simple Binary Trees, Sorting, Algorithm Complexity COMP 282 example topics Graphs, Hash Tables, Balanced Binary Trees, B-Trees (B+, B*, other) Relation between Math and Computer Science There is a close relationship between math, applied math, and computer science. Computer science takes many problems from math and analyzes them from the point of view of calculating or computing a solution. COMP 110/L does not require calculus, but being calculus-ready shows mathematical maturity for programming. Logical and precise thinking is more important than knowledge of calculus. What math skills are important for understanding programming? Algebra • Abstraction • Symbolic manipulation of expressions • Translating word problems into equations for solution Discrete math • Set operations (union, intersection, etc.) • Boolean logic (true, false, and, or, not, if-else, while) Analysis • Functions (set of ordered pairs {(domain, range)}, other equivalent forms) Other (eg, Geometry, Trig, Calculus) • Useful as a problem domain, but course doesn’t specifically require it. • Proofs in geometry are good preparation for problem solving in computer science. Math enters into programming in two distinct ways: • Notation used in programming has been influenced by symbolic notation of algebra. • Math is a source of practice problems for programming exercises.

Page 30: COMP 110 Note Set #1: Problem Solving, Algorithms, …cov/comp110s15/notes/noteset01_intro.pdf · 2015-01-20 · • scientific/numeric calculations (physics, chemistry, engineering)

COMP 110 30 Note Set #1

English composition co-requisite? As part of program preparation, a programmer writes the Java code that makes up the instructions that the computer executes, and the programmer must also prepare supporting information called documentation (comments, manuals, etc.) Communication skills are important for programmers. Interesting problems are too big to be solved by one programmer, so programmers must work in teams. Communication skills are critical for being a good team player.