1 / 20

CSE 1341 - Honors Principles of Computer Science I

CSE 1341 - Honors Principles of Computer Science I. Spring 2008 Mark Fontenot mfonten@engr.smu.edu. Note Set 3. Note Set 3 Overview. Algorithm Activity Diagrams and control structures Blaze through chapter 4 and 5 of text. Algorithm. Method findLargestNumber

arvin
Download Presentation

CSE 1341 - Honors Principles of Computer Science I

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. CSE 1341 - HonorsPrinciples of Computer Science I Spring 2008 Mark Fontenot mfonten@engr.smu.edu Note Set 3

  2. Note Set 3 Overview Algorithm Activity Diagramsand control structures Blaze through chapter 4 and 5 of text

  3. Algorithm Method findLargestNumber input: indexed list of numbers, first index is zero, called arr output: index of largest number store arr[0] in variable high initialize variable x with 0 loop from i = 1 to length of arr if (arr[i] > high) x = i high = arr[i] end if end loop return x end method • Finite ordered list of well-defined actions that can be used to solve a problem in a finite amount of time • Algorithm – to explore logic: • pseudocode • state – transition diagrams • activity diagrams

  4. Our 2nd Diagram – Activity Diagram Sample Activity Diagram • Activity Diagram • models logic • can be used at various levels of detail (30,000 foot view or microscopic view of) • Somewhat similar to flowcharting

  5. Main Activity Diagram Artifacts Ambler, Scott. UML 2 Activity Diagrams, August 20 2006. http://www.agilemodeling.com/artifacts/activityDiagram.htm Initial Node – indicates starting point of logic Final Node – indicates stopping point of logic Activity – rounded rectangle – represents the activities that are taking place Flow - arrow indicating flow of logic Decision – Diamond with one flow entering and two or more exiting

  6. Main Activity Diagram Artifacts (2) Merge – Diamond – two or more flows entering and one exiting Condition – text in square brackets indicated a condition that must be satisfied to traverse its flow. [credentials valid] [credentials not valid] Ambler, Scott. UML 2 Activity Diagrams, August 20 2006. http://www.agilemodeling.com/artifacts/activityDiagram.htm

  7. Examples with pseudocode Guard not required. Why? If x is greater than 60 print “YOU PASSED”

  8. Examples with pseudocode What would the guards be for flows out of this decision? Loop while value is less than 10 value = value + 2

  9. Conditional Constructs if (x > 5) System.out.println(“ YAY! “); if (x < 10 && y > 5) System.out.println(“Whats up?”); else System.out.println(“Go Away!”); switch (myVar) { case 1: x = 5; break; case 2: y = 10; break; default: System.out.println(“Read the directions”); } Execute code based on a condition

  10. New Conditional Construct x > 10 ? y = 5 : z = 3; shortcut for if ( x > 10) y = 5; else z = 3; System.out.println(studentGrade >= 60 ? “Passed” : “Failed”); Conditional Operator (… ? …. : …. ) Shortcut for simple if…else statement Java’s only Ternary Operator

  11. Don’t forget about … if (x > 5) if (y > 10) System.out.println(“You Win!”) else System.out.println(“You Lose!”) What will print if x = 3 and y = 15? … if x = 10 and y = 20? … the dangling else problem

  12. Block public static void main (String [] args) { int x = 3; int y = 0; if (x == 3) { x++; y++ } } Main Block if block • Block • Set of statements that are contained within a pair of braces • Can have nested blocks • main method’s body is a block • can have a block as part of if inside main

  13. Loops • Counter-controlled loops • Loops that iterate for a specified number of iterations • uses counter variable or loop control variable to control iterations • The program shall read 10 grades and produce their average • Sentinel-controlled loops • Number of iterations of loop is not known • end of data entry usually controlled by sentinel value • The program shall read an arbitrary number of grades and the provide the average

  14. Adding method to class Gradebook Add a method to GradeBook to enter 10 grades and the output the total and average. public void determineAverage() { Scanner input = new Scanner(System.in); int total=0, gradeCounter=1, grade, average; while (gradeCounter <= 10) { System.out.print(“Enter Grade: “); grade = input.nextInt(); total = total + grade; gradeCounter++; } average = total / 10; //remember: int division System.out.printf(“\nTotal: %d”, total); System.out.printf(“\nAverage: %d”, average); } counter controlled

  15. Adding method to class Gradebook Add method to GradeBook to determine the average of arbitrary number of grades. public void determineAverage() { Scanner input = new Scanner(System.in); int total=0, gradeCounter=1, grade; double average; //ask user for first grade – could be sentinel System.out.println(“Enter grade or -1 to quit: “); grade = input.nextInt(); while (grade != -1){ total = total + grade; gradeCounter = gradeCounter + 1; System.out.println(“Enter grade or -1 to quit: “); grade = input.nextInt(); } if (gradeCounter != 0) { average = (double)total/gradeCounter; //FP arithmetic System.out.printf(“Average is %.2f\n”, average); } else System.out.println(“No grades entered!”); } Sentinel Controlled

  16. Arithmetic Review int x, y = 5; x = y / 2; System.out.println(x); double x, y = 5; x = y / 2; System.out.println(x);

  17. Casting • Implicit casting • happens for you behind the scenes • int x = 2;double y = 5, z;z = y / x; // x is implicitly converted to double //(promoted) in this case • Explicit casting • programmer can indicate that casting should happen. • place the target data type in parentheses • int x = 2, y = 5;double z;z = (double) y / x; //forcing y to become double //so that we get FP answer

  18. Your turn! Modify calculateAverage (either one) such that it counts the number of passing scores and failing scores and reports this information as well to the user.

  19. Software Engineering • Top – down, Stepwise Refinement • Start at the top and work down until sufficient detail exists to implement in Java • Top represents a single statement that conveys the overall function of the program. • Consider the calculateAverage problem - Possible Top: • Determine the class average for a graded assignment • Above is obviously insufficient: • Initialize VariablesInput, sum and count the gradesCalculate and print the class average • Each step/refinement is a complete representation of the problem/algorithm … only level of detail varies

  20. Second Refinement This is of sufficient detail to implement in Java More refinements may be necessary for more complex problems • Initialize variables can be broken down to: • Initialize total to zeroInitialize counter to zero • Input, sum and count grades can be refined to: • Prompt user to enter first gradeInput the first grade ( may be sentinel)While the user has not yet entered the sentinel Add this grade into the running total Add one to the grade counter Prompt the user to enter the next grade Input the next grade (may be sentinel) • Calculate and print – refined to: • if counter is not equal to zero Set the average to the total divided by the counter Print the averageelse Print “no grades recorded”

More Related