1 / 285

CS 11 – Aug. 27

CS 11 – Aug. 27. Course overview Computers & computer science Nature of problem solving Next, we’ll continue with What software looks like Problem-solving procedure Note: Important terminology highlighted in yellow. Machine that stores and processes information

aurora
Télécharger la présentation

CS 11 – Aug. 27

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 11 – Aug. 27 • Course overview • Computers & computer science • Nature of problem solving • Next, we’ll continue with • What software looks like • Problem-solving procedure Note: Important terminology highlighted in yellow.

  2. Machine that stores and processes information With memory, machine can be programmed. Memory stores software and other files. Information inside memory is all in binary! CPU’s job is to obey instructions from a program. What is a computer? Memory CPU + * – / % √  Σ file file file

  3. What is CS ? • The study of how we … • Solve problems • Represent information • In problem solving, we’d like: • Find systematic ways of going about solution • Correct, quick and informative solutions. • Information can be: • Different types: numbers, text, images, sound, the software itself • The input and output to a computer program

  4. Problems • The earliest problems given to a computer were mathematical. • Sometimes there is no clean formula • Many equations can’t be solved analytically. For example, cos(x) = x. Need to solve numerically. • Ex. Heat equation is a partial differential equation (PDE). Most PDEs have to be solved numerically. • Ex. Calculating a square root. • And even if there is a clean formula, a computer can help you automate the calculations.

  5. Problems (2) • “Mathematical” problems may at first sound boring. But they include many useful applications • Ex. Finding directions • Other kinds of problems for the computer • Games • Record keeping, managing investments, … • Networking, communication • Multimedia (e.g. image processing) • Of course, much more!

  6. Software • Powerful! • We get to tell the machine exactly what we want. • Sometimes, existing programs like Excel or Photoshop are not enough. • Program = sequence of instructions for CPU to obey. • Works like a recipe. • A recipe has: ingredients, steps, and result is food! • A program has: input, calculations, output.  When we start to look at programs, be on the lookout for these 3 parts.

  7. A program’s input may be: Numbers Text File URL Button / click Image (rarely) Sound (rarely) A program’s output may be: Numbers Text File (even HTML) Image Sound (rarely) I/O In this class, we’ll be able to read and create files, interact with the Web, and create images.

  8. Program parts • To reiterate: 3 parts are input, calculations, output. • We’ll spend most effort on calculations. • I should give this part a better name, because it’s mostly not arithmetic. “Logic” or “strategy” may be a more descriptive name. • Goal of CS-11: To be able to solve problems using a variety of I/O and calculation strategies.

  9. CS 11 – Aug. 28 Overview, continued • “recipe” analogy • Languages for the computer • What does software look like? • Problem-solving procedure

  10. Recipes • Cooking may be a good analogy, because it’s solving a specific problem “I’m hungry.”  • What do we see in recipes? Here’s one: • Brown the beef 15 min. Drain grease. • Dice carrot, celery, onion (aka “mirepoix”) • Cut up and boil 6 potatoes until soft. • Mash potatoes • Add flour, spices, sauce, mirepoix to beef. • Put meat mixture into casserole, top with potatoes. • Bake in oven at 400 for 30 minutes.

  11. Recipes (2) • A computer program has some of the same elements as a recipe… • In recipes we see: • Ingredients (the “nouns” of the problem) • Steps to perform (the “verbs”) • In some steps, we continue/wait for something • Although it’s not obvious, sometimes we check things: • Are potatoes fully mashed? • Should I add more _____ to the mixture?

  12. Recipes (3) • But we don’t eat the same stuff every day. Once we know a few recipes, we can put together a menu for choices. if (have all ingredients), make Shepherd’s pie. if (no potatoes), just make soup instead. if (no veggies), make hamburger. if (no beef), make pasta. • When you view a whole menu as a program, then “making soup” becomes a sub-program. • A large program is composed of several parts. • In industry, sometimes each part implemented by different people. A kitchen may have many chefs.

  13. Summary • Computer science is a problem-solving discipline. • Many kinds of problems, and the I/O can take various forms. • Writing our own software exploits the full power of the computer! • Every solution (program) should have a well-defined structure, such as listing the ingredients and steps for input, calculations and output.

  14. Programming language • English? • Ambiguities, relies on context • Binary? • Tedious, error-prone! • In this class, the Java language will be our vehicle for solving problems. • Turns out to be easier to write larger programs. Forces us to have a well-structured solution. • Many built-in features to support graphics and the Web. Java was specifically designed for Web applications. • Use compiler to translate our program into binary.

  15. Compiling Java program Byte code Java compiler Can execute in CPU. Compiler reads your program. It checks for simple mistakes, and then translates your code into binary.

  16. Practical matters • Compiler • This is a program that translates your Java code into “byte code” that can be executed on the machine. • Files and folders • Each source file you type will be a text file whose name ends in .java • Two kinds of programs • Simple – can be accomplished in one sitting, one source file. Many of our early examples will be like this. • Not-so-simple – requires a definite plan. Multiple source files, one for each “big noun” or class.

  17. Program • What does a computer program consist of? Has these parts: • Begin with a comment describing the problem and solution for a human reader. • Tell Java system what built-in libraries we are going to use (if any). • special ingredients already prepared by somebody else • Why is spaghetti so easy? • Common ingredients we’ll use are System, Scanner, Math. • Code: use variables and specify steps for our input, calculations, output

  18. Simple examples • You don’t have to know a lot of Java to solve these problems: • Print a message and halt. (This program would only do output.) • Add two numbers and report answer. (Sounds easy, but features input, calcs, output!) Once we solve this problem, we’d be tempted to improve on it, and make it more general.

  19. Lab • Let’s practice running simple programs on the computer. • Make sure you have an account, and you know your password. • Follow directions on lab handout.

  20. CS 11 – Aug. 29 • How to do I/O • Problem-solving procedure. • You can find class notes on cs.furman.edu/~chealy/cs11

  21. Scanner • When reading input, we can use the built-in Scanner. (See BasicProgram handout.) Scanner kbd = new Scanner(System.in); Says that we want to create a scanner, based on the keyboard input, which Java calls System.in. int input = kbd.nextInt(); • When you want to read an integer, call the function nextInt(); • Again, don’t worry about every single detail at this point.

  22. printf • Formatted printing • Designed to print a string in quotes, possibly with extra information such as variables. System.out.printf(“Hello.\n”); System.out.printf(“answer = %d\n”, answer); • Usually a good idea for the string to end: \n • Represents the newline character. Whatever follows will then be on the next line. • Special codes use the % symbol.

  23. Format codes • %d = decimal integer • %f = real number • %s = string • %c = single character (not often used) Example: int quantity = 4; double costEach = 7.99; double total = quantity * costEach; System.out.printf(“%d bottles cost $ %f\n”, quantity, total); But the output is $ 31.960000

  24. Specifying precision • The default precision for %f is 6 decimal places. • You can specify precision by putting the desired number of decimal places right before the ‘f’. • Use %.2f to say you want exactly 2 decimal places • %.1f would mean 1 decimal place. So we need to change the earlier output statement to: System.out.printf(“%d bottles cost $ %.2f\n”, quantity, total);

  25. Problem solving • Need to have a plan! • Often a bad idea to rush to keyboard and start typing code. • Problem solving procedure: (See handout) • design • implementation

  26. Advice • To learn problem-solving, must practice • Look at examples ( This is not a theory course  ) • Use built-in features of Java to simplify your soln. These built-in libraries are collectively known as the API: Application Programmer Interface. http://java.sun.com/j2se/1.5.0/docs/api/ • One major skill is identifying the major “nouns” and “verbs” in problem description. • In larger programs, structure is based on the nouns.

  27. Advice (2) • It’s been said that any skill takes about 10 years to master. In 3 months you won’t be expected to solve every possible problem. So, be patient with yourself and have some fun. • Problem solving isn’t easy. There is no formula that works in all cases. A problem could arise at any time in the process. Ask me for help if stuck! • It’s easier to find a mistake in (English) design than in the (Java) implementation. This is why the early steps are important. Again, don’t rush to type code.

  28. Example • Let’s look at an example problem: The post office problem. Ask the user for the number of post cards and letters that need to be sent, and compute the total postage, assuming the costs for one of each are 26 and 41 cents. • In our solution, we’ll need • Variables to store numbers. • Format the output so it looks like money.

  29. CS 11 – Sept. 3 Fundamental ideas • Practice the problem-solving procedure • Statements • Variables: names and types • More about Scanner for input

  30. Example • Let’s look at an example problem: The post office problem. Ask the user for the number of post cards and letters that need to be sent, and compute the total postage, assuming the costs for one of each are 27 and 42 cents. • In our solution, we’ll need • Variables to store numbers. • Format the output so it looks like money. • Once finished, we can enhance solution. • Special message if over $10.

  31. Overview of statements Fundamental unit of a program • Must end in a semicolon. Examples of statements - • Assigning a value to a variable • If this is the first time we’re using the variable, it must also be declared. • Input / output • Calling a function: delegating work to another part of the program • Making choices: if-statement, … • Doing things multiple times : while-statement, … (this is called a loop)

  32. Variables • Contain values we manipulate. • Must be declared before they are used. • Identifier = name of a variable • Rule: must begin with letter or _, rest of name may also contain digits • Conventions: • Should have a meaningful “noun” name • Should avoid _ • Should begin with lowercase letter. If multiple words in name, capitalize 2nd, 3rd, … words.

  33. Variables (2) • Formats of declaration type identifier; type identifier = initial value; // better  • Common variable types: int, double, char, String • Other types you may see: byte, short, long, boolean, float • Type names beginning with lowercase letter are the 8 primitive types (small nouns) of Java.

  34. Primitive types

  35. Scanner Commonly used scanning functions: • nextInt() – grab the next integer • nextDouble() – grab the next real # • next() – grab the next word • nextLine() - get the whole rest of the line • There are also “has” functions (e.g. hasNextInt() ) that test to see if there actually is an integer, real number, etc. We’ll use these later.

  36. Scanner (2) • Let’s apply what we know • We can declare and use variables of various types. • The Scanner can get input of various types. • Examples String name = kbd.next(); double length = kbd.nextDouble(); int size = kbd.nextInt(); • Pay close attention to the types. They must agree. For example, the following is bad: double height = kbd.nextInt();

  37. Summary • A program is a sequence of statements. • e.g. assignment stmt., input stmt., output stmt., … • We use variables • Variables have a type • Must be declared before use • Scanner & printf can handle many types 

  38. Next Example: F/C • Design a program that allows the user to convert from Fahrenheit to Celsius, or the other way around. Do you want F  C or C  F ? Do F  C Do C  F

  39. CS 11 – Sept. 4 • Review what we know • Problem solving procedure • Basic parts to a program • Statements & variables • If-statement • Comparisons: < > == etc.

  40. If-statement • Use to ask a question if (amt < 10.00) if (num < 0) no credit card number is negative • Often we have an alternative to handle. So we use the word else. if (hours > 40) overtime pay formula else regular pay formula // Let’s work out this example!

  41. Overtime • Hourly employee. hours = Hours worked rate = Hourly rate • Let’s assume overtime rate is 1.5x if (hours <= 40) pay = hours * rate; else pay = 40 * rate + (hours – 40) * (rate * 1.5);

  42. Divisibility • Often we want to know if an integer is divisible by something. • For leap year, divisible by 4. • Even number: divisible by 2. • Prime number: divisible by almost nothing! • We use % with an if-statement. Here is even: if (num % 2 == 0) System.out.printf(“number is even\n”); else System.out.printf(“number is odd\n”);

  43. Example: F/C • Design a program that allows the user to convert from Fahrenheit to Celcius, or the other way around. Do you want F  C or C  F ? Do F  C Do C  F

  44. Lab • Each program should be in its own folder. • You’ll be given incomplete source files. • Design phase – We would type only the minimal structure of our program ahead of time. (WordPad) • Implementation phase – • Open Eclipse, create “project”, telling it where your source files are. • Compile and run whenever you like. • Finish typing code here.

  45. CS 11 – Sept. 5 • Ideas from lab • FC: type of an expression & conversions • Paint: intermediate calculations • Using / and % • More about the if-statement • Leap year example • Testing multiple conditions • Next week: String data type • Let’s have a tutorial on Tuesday, room 200-F

  46. Expression type • Sometimes we need to convert integer expression into real numbers. • In FC program, beware of typing 9/5 and 5/9 ! • Use real-number constant. 9.0 / 5 • But what if we want a / b and they’re both int? • Can multiply by 1.0 1.0 * a / b • Can use a cast before the variable. (double) a / b • Extra parens are ok, but don’t type: (double) (a / b) ! • Ex. Converting win-loss record  % wins.

  47. Paint calculations… • We used intermediate calculations for area of room, gallons of paint… finally cost of paint. • Don’t write just one “silver bullet” formula.  • If you need to round a real number to an integer • Can use Math.round( ), Math.ceil( ) or Math.floor( ) • Can cast a double as an int: e.g. (int) 8.7 equals 8. • Note about the lab: We didn’t do any error checking of input. We’ll learn about this later.

  48. / and % • Integer division is still useful / gives quotient and % gives the remainder. • Ex. Counting change • Given # of cents (1-99), tell how many of each type of coin. • Ex. If num is an integer, what are…? num % 10 num % 100

  49. Review of if • if statements look like this: if (question) if (question) statement { block of statement(s) } • The “question” is usually a comparison as in if (num % 2 == 0) ... • It’s optional to have an else portion underneath

  50. Leap years • Remainders can help  • Simple approach: if (year % 4 == 0) … • Full definition: if the year ends in 00, it must be divisible by 400, otherwise it just needs to be divisible by 4 • To write as if-statement, we need special operators for: AND……… && OR……….. ||

More Related