Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 3.

Similar presentations


Presentation on theme: "Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 3."— Presentation transcript:

1 Spring 2008 Mark Fontenot mfonten@engr.smu.edu CSE 1341 Principles of Computer Science I Note Set 3

2 Algorithm 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 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

3 Object Oriented vs. Structured Object Oriented for arranging objects and interactions Structured for dealing with detailed logic of how things are done can be affected by design of the objects. Example: Car Object But there is a sequence of steps that occur when you press the gas pedal.

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

5 Main Activity Diagram Artifacts 5 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 Ambler, Scott. UML 2 Activity Diagrams, August 20 2006. http://www.agilemodeling.com/artifacts/activityDiagram.htm

6 Main Activity Diagram Artifacts (2) 6 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 7 If x is greater than 60 print “YOU PASSED” Guard not required. Why?

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

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

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

11 Don’t forget about … … the dangling else problem 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?

12 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 public static void main (String [] args) { int x = 3; int y = 0; if (x == 3) { x++; y++ } Main Block if block

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 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); } Add a method to GradeBook to enter 10 grades and the output the total and average. counter controlled

15 Adding method to class Gradebook 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!”); } Add method to GradeBook to determine the average of arbitrary number of grades. 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 Variables Input, sum and count the grades Calculate and print the class average Each step/refinement is a complete representation of the problem/algorithm … only level of detail varies

20 Second Refinement Initialize variables can be broken down to: Initialize total to zero Initialize counter to zero Input, sum and count grades can be refined to: Prompt user to enter first grade Input 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 average else Print “no grades recorded” This is of sufficient detail to implement in Java More refinements may be necessary for more complex problems


Download ppt "Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 3."

Similar presentations


Ads by Google