Selection and Repetition Revisited

Similar documents
Selection and Repetition

Selection and Repetition Revisited

Selection and Repetition

Selection Statements and operators

Selection Statements and operators

Java I/O and Control Structures

Java I/O and Control Structures Algorithms in everyday life

CSC 1051 Data Structures and Algorithms I

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Algorithms and Conditionals

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Introduction to Arrays

Conditional Statements

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Java Flow of Control

2: Basics of Java Programming

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Chapter 3. Selections

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Using Classes and Objects

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Iterators and File Input

Arrays, Part 3: Multidimensional arrays

Top-Down Program Development

Basics of Java Programming variables, assignment, and input

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

Name: Checked: Preparation: Response time experiment accessing the system clock

Lecture 3: Variables and assignment

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

Introduction to Computer Science Unit 2. Exercises

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Conditionals and Loops

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Last Class. While loops Infinite loops Loop counters Iterations

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Conditional Programming

CS111: PROGRAMMING LANGUAGE II

Java Coding 3. Over & over again!

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

Where do objects come from? Good question!

CompSci 125 Lecture 11

Control Structures in Java if-else and switch

CMPT 125: Lecture 4 Conditionals and Loops

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Topic 11 Scanner object, conditional execution

1 Short Answer (10 Points Each)

File I/O and Exceptions

BLOCK STRUCTURE. class block main method block do-while statement block if statement block. if statement block. Block Structure Page 1

Introduction to Computer Science Unit 2. Notes

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

CS 106 Introduction to Computer Science I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

AP CS Unit 3: Control Structures Notes

Introduction to Java Applications

Chapter. Let's explore some other fundamental programming concepts

Repetition CSC 121 Fall 2014 Howard Rosenthal

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Topic 11 Scanner object, conditional execution

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

Data Representation Classes, and the Java API

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures in Java if-else and switch

Chapter 2: Using Data

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

COMP 202 Java in one week

Chapter 02: Using Data

The Java language has a wide variety of modifiers, including the following:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Course PJL. Arithmetic Operations

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

COMP 202. Java in one week

Object Oriented Programming with Java

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Transcription:

Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus

Selection structures in Java Conditional statement: if (n > 0) System.out.print("positive"); else System.out.print("negative"); Other selection structures (Chapter 6 in text) the conditional operator the switch statement

The Conditional Operator Syntax condition? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression Example: Rewrite this à if (n > 0) System.out.print("positive"); else System.out.print("negative");

The conditional operator is not a statement WRONG!

More examples: int bit = (ans.equalsignorecase("yes")? 1: 0); String status = (age < 18? "child" : "adult"); The conditional operator requires three operands so it is sometimes called the ternary operator Hands on: try this in the Person class!

Try this: Using if/else: if (happiness) page.drawarc (x+15, y+30, 20, 10, 180, 180); else page.drawarc (x+15, y+30, 20, 10, 0, 180); Rewrite using conditional operator:

Try this: Rewrite this statement so that "Dime" is printed if num equals 1. System.out.println ("Your change is " + num + "Dimes")); use conditional operator:

The switch Statement: multi-way branches Recall: Logic of an if-else statement

The switch Statement: multi-way branches switch statement logic expression evaluated statement1 case: 1 case: 2 statement2 case: 3 statement3 Note: this is a simplified flowchart of the logic of the switch statement

The switch Statement - example public String tostring() String result = ""; switch (facevalue) case 1: result = "one"; break; case 2: result = "two"; break; case 3: result = "three"; break; return result; Hands on: try this in the Die class!

The switch Statement in general switch ( expression ) case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3... default: statement-list-n integer, char, or enumerated types (Java 7 also allows Strings) NO floating point values NO ranges of values (eg: 0<x<10) If expression matches value2, control jumps to here If none of the values match the expression, control jumps to here

So the logic of the switch is more like this: expression evaluated 1 2 3 statements1 statements2 statements3 Note: this is still a simplified flowchart of the logic of the switch statement

GradeReport.java //******************************************************************** // GradeReport.java Author: Lewis/Loftus // // Demonstrates the use of a switch statement. //******************************************************************** import java.util.scanner; public class GradeReport //----------------------------------------------------------------- // Reads a grade from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) int grade, category; continue Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextint(); category = grade / 10; System.out.print ("That grade is ");

Sample Run continue Enter a numeric grade (0 to 100): 91 switch (category) That grade is well above average. Excellent. case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); Hands on: try removing one of the break statements

Another example SwitchExample.java //*********************************************************************** // SwitchExample.java Author: M A Papalaskari // Example of switch statement that does NOT use break after each case. //*********************************************************************** import java.util.scanner; public class SwitchExample // Example of using a switch statement. Counts number of digits, zeros, // whitespace, and others in a line of input. public static void main (String[] args) Scanner scan = new Scanner(System.in); int digits = 0, zeros = 0, whitespace = 0, other = 0; System.out.print("Input line>"); String message = scan.nextline(); continue int count = 0; Sample Run¼¼ Input line>10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Lift off! 11 Digits, of which 1 is a zero 11 whitespace 18 others

while (count < message.length()) switch (message.charat(count)) case '0': zeros++; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': digits++; break; case ' ': case '\t : whitespace++; break; default: other++; // end switch count++; // end while System.out.print(digits + " Digit" + (digits==1? "" : "s")); System.out.print(", of which " + zeros); System.out.println((zeros==1? " is a zero " : " are zeros ")); System.out.println(whitespace + " whitespace"); System.out.println(other + " other" + (other==1? "" : "s"));

Loops revisited: do & for loops Repetition structures in Java, so far: while loop: int count = 0; while (count < 5) System.out.println (count); count++; Other repetition structures (Chapter 6 in text) the do loop the for loop

The do Statement in Java A do statement has the following syntax: do statement-list; while (condition); //end do The statement-list is executed once initially, and then the condition is evaluated The statement-list is executed repeatedly until the condition becomes false

The while and do loops are similar. int count = 0; while (count < 5) System.out.println (count); count++; int count = 0; do System.out.println (count); count++; while (count < 5);

Similar but not the same: while Loop do Loop condition evaluated true statement int count = 0; while (count < 5) System.out.println (count); count++; false true statement condition evaluated false int count = 0; do System.out.println (count); count++; while (count < 5); The body of a do loop executes at least once

Try this: Write a do loop to print the even numbers from 2 to 100.

For some things the do loop is more appropriate: System.out.println( input a number >5 ); int num = scan.nextint(); while (num <= 5) System.out.println ( type a number >5 ); num = scan.nextint(); do System.out.println ( type a number >5 ); num = scan.nextint(); while (num <= 5); input validation

For some things the do loop is more appropriate: int answer = 1; while (answer == 1) do System.out.print( Enter QP "); System.out.print( Enter QP "); qp = scan.nextint(); qp = scan.nextint(); System.out.print ("Enter Credits "); credits = scan.nextint(); gpa = (double) qp /credits; System.out.println("GPA = " + gpa); System.out.print("Again? 1=yes,0=no "); answer = scan.nextint()); System.out.println("Thank you. Goodbye."); System.out.print ("Enter Credits "); credits = scan.nextint(); gpa = (double) qp /credits; System.out.println("GPA = " + gpa); System.out.print("Again? 1=yes,0=no "); while (1 == scan.nextint()); System.out.println("Thank you. Goodbye."); repeating a computation

Another example: ReverseNumber.java //******************************************************************** // ReverseNumber.java Author: Lewis/Loftus Sample Run // Demonstrates the use of a do loop. //******************************************************************** Enter a positive integer: 2896 import java.util.scanner; That number reversed is 6982 public class ReverseNumber //----------------------------------------------------------------- // Reverses the digits of an integer mathematically. //----------------------------------------------------------------- public static void main (String[] args) int number, lastdigit, reverse = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter a positive integer: "); number = scan.nextint(); do lastdigit = number % 10; reverse = (reverse * 10) + lastdigit; number = number / 10; while (number > 0); System.out.println ("That number reversed is " + reverse); Copyright 2012 Pearson Education, Inc.

Another example: EvenOdd.java /******************************************************************** // EvenOdd.java Author: Lewis/Loftus // Demonstrates the use of the JOptionPane class. //******************************************************************** import javax.swing.joptionpane; The JOptionPane class provides methods for creating dialog boxes public class EvenOdd //----------------------------------------------------------------- // Determines if the value input by the user is even or odd. // Uses multiple dialog boxes for user interaction. //----------------------------------------------------------------- public static void main (String[] args) String numstr, result; int num, again; do numstr = JOptionPane.showInputDialog ("Enter an integer: "); num = Integer.parseInt(numStr); result = "That number is " + ((num%2 == 0)? "even" : "odd"); JOptionPane.showMessageDialog (null, result); again = JOptionPane.showConfirmDialog (null, "Do Another?"); while (again == JOptionPane.YES_OPTION); Copyright 2012 Pearson Education, Inc.

/******************************************************************** // EvenOdd.java Author: Lewis/Loftus // Demonstrates the use of the JOptionPane class. //******************************************************************** import javax.swing.joptionpane; public class EvenOdd //----------------------------------------------------------------- // Determines if the value input by the user is even or odd. // Uses multiple dialog boxes for user interaction. //----------------------------------------------------------------- public static void main (String[] args) String numstr, result; int num, again; do numstr = JOptionPane.showInputDialog ("Enter an integer: "); num = Integer.parseInt(numStr); result = "That number is " + ((num%2 == 0)? "even" : "odd"); JOptionPane.showMessageDialog (null, result); again = JOptionPane.showConfirmDialog (null, "Do Another?"); while (again == JOptionPane.YES_OPTION); Copyright 2012 Pearson Education, Inc.

for: a loop with built in counter initialization condition evaluated true false statement increment

for: a loop with built in counter initialization int count = 0; Example condition evaluated true statement false while (count < 5) System.out.println (count); increment count++;

for: a loop with built in counter for (int count = 0; count < 5; count++) System.out.println (count); initialization int count = 0; Example condition evaluated true statement false while (count < 5) System.out.println (count); increment count++;

The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) statement; increment; for ( initialization ; condition ; increment ) statement;

The for Statement A for statement has the following syntax: The initialization is executed once before the loop begins The condition is tested after the initialization and again before each iteration; for ( initialization ; condition ; increment ) statement; the statement is executed while The condition is true The increment is executed at the end of each iteration

The for Statement - Example A for statement has the following syntax: The initialization is executed once before the loop begins The condition is tested after the initialization and again before each iteration; for (int count = 0; count < 5; count++) System.out.println (count); the statement is executed while The condition is true The increment is executed at the end of each iteration

The for Statement The increment section can perform any calculation: for (int num=100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

Try this: Write a for loop to print the even numbers from 2 to 100.

Example: ReverseNumberAsString.java //******************************************************************** // ReverseNumberAsString.java Author: MAP // Demonstrates the use of a for loop. //******************************************************************** import java.util.scanner; Sample Run public class ReverseNumberAsString Enter a positive integer: 2896 That number reversed is 6982 //----------------------------------------------------------------- // Reverses the digits of an integer viewed as a String. //----------------------------------------------------------------- public static void main (String[] args) int number; String reverse = ""; Scanner scan = new Scanner (System.in); System.out.print ("Enter a positive integer: "); number = scan.nextint(); String original = Integer.toString(number); for (int i=0; i<original.length(); i++) reverse = original.charat(i) + reverse; System.out.println ("That number reversed is " + reverse);

Example: Stars.java //******************************************************************** // Stars.java Author: Lewis/Loftus // // Demonstrates the use of nested for loops. //******************************************************************** public class Stars //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. //----------------------------------------------------------------- public static void main (String[] args) final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); Output * ** *** **** ***** ****** ******* ******** ********* ********** Exercise: can you make it print the row number in (1, 2, 3 ) at the beginning of each line?