1 / 39

COMP 14 Introduction to Programming

This class covers the selection and repetition statements in programming, including if-else statements, switch statements, and various kinds of loops. Learn how to write effective selection and repetition statements in Java.

wkeri
Download Presentation

COMP 14 Introduction to Programming

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. COMP 14Introduction to Programming Mr. Joshua Stough February 14, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218

  2. Announcements • Tomorrow (2/17) is the last day to drop classes • Program 2 • only required to accept one mathematical operation in the format: operand1 operator operand2 • Mid-Term Exam • March 3 (2 weeks from Wednesday)

  3. One-Way Selection if (expression) if (expression) { statement statement(s) }

  4. Two-Way Selection if (expression) statement1 else statement2 if (expression) {statement(s)1 } else { statement(s)2 }

  5. Two-Way SelectionAnd White Space if (expression) {statement(s) } else { statement(s) } if (expression) {statement(s) } else { statement(s) } if (expression) {statement(s) } else { statement(s) }

  6. The switch Statement switch (expression) { casevalue1: statements1 break; casevalue2: statements2 break; case value3: statements3 break; default: statements }

  7. switch and nested if-else switch (expression) { casevalue1: statements1 break; casevalue2: statements2 break; case value3: statements3 break; default: statements } if (expression == value1) { statements1 } else if (expression == value 2) { statements2 }else if (expression == value 3) { statements3 } else { statements }

  8. Writing Selection StatementsWhat Type of Construct To Use? • Only need to execute additional statements if condition is true • Need to execute separate additional statements based on if the condition is true or false • Need to execute different statements based on multiple conditions • Need to execute different statements based on an expression that evaluates to a char or int if if-else nested if-else switch

  9. Writing Selection Statements • Write the outline of the selection statement • keywords • curly braces • case and break statements (for switch) • Write the expression • boolean expression, or condition • expression or variable evaluating to char or int • Write statements that execute based on the condition

  10. Example Write a selection statement that sets grade to 'F' if score is less than 60 and sets grade to 'P' if score is greater than or equal to 60. 3) Add condition if (score < 60) { } else { } 1) Choose construct if-else 2) Write outline if ( ) { } else { } 4) Add statements if (score < 60) { grade = 'F'; } else { grade = 'P'; }

  11. Questions What type of selection statement should be used? • Print "Male" if gender is 'M' and "Female" if gender is 'F'. • Print the state associated with areaCode, where areaCode is an int. • Print the maximum of three integers. if-else switch nested if-else

  12. Question Assume that the lengths of 3 sides of a triangle are given in the integer variables side1, side2, and side3. Write code that will print: • "Equilateral" if all three sides are equal • "Isosceles" if only two sides are equal • "Scalene" if no sides are equal equilateral isosceles scalene First, what selection construct should be used? nested if-else

  13. Answer // side1, side2, and side3 are lengths // of the sides of a triangle if (side1 != side2 && side2 != side3 && side1 != side3) { // no sides are equal System.out.println ("Scalene"); } else if (side1 == side2 && side2 == side3) { // all sides are equal System.out.println ("Equilateral"); } else { // two sides are equal System.out.println ("Isosceles"); }

  14. Today in COMP 14 • Repetition statements • while loops • Textbook Reference: Chapter 5 (pgs. 200-214)

  15. Why Is Repetition Needed? • Want to add 5 integers to find their average? • declare a variable for each integer • initialize the sum • read in the user input one at a time • sum the numbers • take the average • Want to add 1000 integers to find their average? • declare one variable for input • initialize the sum • read in one line of user input • add to the sum • take the average repeat steps 3 and 4 1000 times

  16. Repetition Statements • Allow us to execute a statement multiple times • Often referred to as loops • Controlled by boolean expressions • like selection, or conditional, statements • Java has three kinds of repetition statements: • the while loop • the for loop • the do loop

  17. Loops • Must use a loop control variable • controls how many times to loop • 4 Parts to Every Loop • initialization - set loop control variable before condition • condition - when to stop • update - change to the loop control variable • body - actions to repeat

  18. Typical Uses of Loops • Repeat a section of code a specified number of times - counter-controlled • Repeat a section of code (reading input) until the a specific value is read - sentinel-controlled • Repeat a section of code (reading input) until a valid value is entered - input validation • Repeat a section of code (reading from a file) until the end of the file is reached - EOF-controlled • Repeat a section of code until a boolean variable becomes false - flag-controlled

  19. while is a reserved word If the condition is true, the loop body is executed. Then the conditionis evaluated again. The while LoopSyntax while ( condition ) { loop body; } The loop body is executed repeatedly until the condition becomes false.

  20. The while Loop • Syntax while (expression) statement • Expression is always true in an infinite loop • Statements must change value of expression to false

  21. The while LoopExample final int LIMIT = 3; int count = 0; while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); boolean condition Output: 0 1 2 All done! initialization loop body update

  22. final int LIMIT = 3; int count = 0; while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); LIMIT count Output: The while LoopWhat's Going On? 3 0 1 2 3 0 1 2 All done!

  23. The while Loop final int LIMIT = 3; int count = 0; while (count < LIMIT) { count++; System.out.println (count); } System.out.println (“All done!”); Output: 1 2 3 All done!

  24. The while Loop final int LIMIT = 3; int count = 0; while (count < LIMIT) { System.out.println (count); } System.out.println (“All done!”); Output: 0 0 0 0 0 0 0 0 0 0 ...

  25. The while Loop final int LIMIT = 3; int count = 0; while (count <= LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); Output: 0 1 2 3 All done!

  26. The while Loop • If the condition of a while statement is false initially, the loop body is never executed • The body of a while loop will execute zero or more times

  27. Counter-Controlled while Loop • Used when exact number of times statements should execute is known • Basic Form: counter = 0; while (counter < N) { ... counter++; ... } N is the number of times the loop should execute

  28. Example final int NUM_STUDENTS = 100; int sum = 0; double average; int i = 0; // initialize loop control var while (i < NUM_STUDENTS) { sum += Integer.parseInt(inFile.readLine()); i++; // update loop control variable } average = (double) sum / NUM_STUDENTS; Often we use i, j, k as counter variable names.

  29. Reading From a File • How do you know how many items there will be? • ask the user • arrange the data file so that the first item is the number of items in the file • Other ways to read all of the items: • use sentinel value • read until end-of-file (EOF)

  30. Sentinel-Controlled while Loop • Used when exact number of entry pieces is unknown but last entry (special / sentinel value) is known • Basic Form: input the first data item into variable while (variable != sentinel) { ... input a data item into variable }

  31. Example int i = 0, sum = 0, score; final int SENTINEL = -99; double average; // initialize the loop control variable score = Integer.parseInt(inFile.readLine()); while (score != SENTINEL) { sum += score; // update the loop control variable score = Integer.parseInt(inFile.readLine()); } average = (double) sum / NUM_STUDENTS;

  32. Average.java Example • Read in integers and print their sum until the user enters 0 • Print the average of the numbers entered

  33. Input Validation while Loop • Used to ensure that the user enters valid input • Basic Form: input the first data item into variable while (variable is not in valid range) { ask the user for valid input input a data item into variable }

  34. Example int num; // initialize loop control variable System.out.print (“Enter a number [0-100]: "); num = Integer.parseInt(keyboard.readLine()); while ((num < 0) || (num > 100)) { System.out.println (num + " is not [0-100]"); System.out.print (“Enter a number: “); // update the loop control variable num = Integer.parseInt(keyboard.readLine()); } System.out.println (“You entered “ + num);

  35. WinPercentage.java Example • Ask user for number of games won between (0 - 12) • Keep asking until get a number between (0 - 12) • Compute the winning percentage

  36. Flag-Controlled while Loop • Boolean value used to control loop • Basic Form: boolean found = false; while (!found){ ... if(expression) found = true; ... }

  37. EOF-Controlled while Loop • Used when input is from a file • Sentinel value is not always appropriate • Basic Form: inputLine = inFile.readLine(); while (inputLine != null) { ... inputLine = inFile.readLine(); } null is a reserved word

  38. TelephoneDigitProgram.java • In textbook pg. 209-210 • Ask user for uppercase letter • Print telephone digit for that letter • Enter 'Q' or 'Z' to quit

  39. Next Time in COMP 14 • for loops • do...while loops • Reading: Ch 5 (pgs. 229-247)

More Related