CompSci 125 Lecture 11

Similar documents
Controls Structure for Repetition

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

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

CompSci 125 Lecture 09. Chapter 5: while, break and continue statements Iterators and the ArrayList Class

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Chapter 4: Control structures. Repetition

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

FLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

Repetition, Looping. While Loop

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Control Structures II. Repetition (Loops)

Chapter 4: Control structures

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

CS111: PROGRAMMING LANGUAGE II

Loops. CSE 114, Computer Science 1 Stony Brook University

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Control Structures in Java if-else and switch

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Computer Programming I - Unit 5 Lecture page 1 of 14

Introduction. C provides two styles of flow control:

STUDENT LESSON A12 Iterations

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Introduction to the Java Basics: Control Flow Statements

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Control Structures in Java if-else and switch

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

switch-case Statements

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

ECE 122. Engineering Problem Solving with Java

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

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

204111: Computer and Programming

CSC Java Programming, Fall Java Data Types and Control Constructs

Introduction to Java & Fundamental Data Types

Java Control Statements

Arithmetic Compound Assignment Operators

Lecture 14. 'for' loops and Arrays

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

More on control structures

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Repetition, Looping CS101

CS 101 Spring 2007 Midterm 2 Name: ID:

Lecture Set 4: More About Methods and More About Operators

Java Flow of Control

Iteration statements - Loops

CS1004: Intro to CS in Java, Spring 2005

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

CS111: PROGRAMMING LANGUAGE II

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Topic 5: Enumerated Types and Switch Statements

CS171:Introduction to Computer Science II

++x vs. x++ We will use these notations very often.

CS171:Introduction to Computer Science II

5) (4 points) What is the value of the boolean variable equals after the following statement?

Accelerating Information Technology Innovation

Advanced if/else & Cumulative Sum

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

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

AP Programming - Chapter 6 Lecture

Control Statements Loops

Top-Down Program Development

The Basic Parts of Java

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Flow Control. Key Notion. Statement Categories. 28-Oct-10

Repetition Structures

1007 Imperative Programming Part II

Loops and Expression Types

CS 106 Introduction to Computer Science I

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

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

Object-Oriented Programming

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Lecture 8 CSE11 Fall 2013 While Loops, Switch Statement, Simplifying Conditionals

Programming with Java

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Course Outline. Introduction to java

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

H212 Introduction to Software Systems Honors

Lesson 10..The switch Statement and char

CS313D: ADVANCED PROGRAMMING LANGUAGE

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Bjarne Stroustrup. creator of C++

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

ECE 122. Engineering Problem Solving with Java

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Transcription:

CompSci 125 Lecture 11 switch case The? conditional operator do while for

Announcements hw5 Due 10/4 p2 Due 10/5

switch case!

The switch case Statement Consider a simple four-function calculator 16 buttons: 0..9, +, -, /, *, =, Clear Each button press causes one of 16 code blocks to execute You could write this up with 16 if statements But switch case provides a somewhat cleaner approach Java can sometimes generate more efficient code

Example switch Statement String season;! Scanner stdin = new Scanner(System.in);! int month = stdin.nextint();! switch (month) {! case 1: System.out.println( Winter );! case 4: System.out.println( Spring );! case 7: System.out.println( Summer );! case 11: System.out.println( Fall );! }!!!

Using a default case String season;! Scanner stdin = new Scanner(System.in);! int month = stdin.nextint();! switch (month) {! case 1: System.out.println( Winter );! case 4: System.out.println( Spring );! case 7: System.out.println( Summer );! case 11: System.out.println( Fall );! default: System.out.println( Ignored );! }!!!

Multiple case Labels String season;! Scanner stdin = new Scanner(System.in);! int month = stdin.nextint();! switch (month) {! case 1:! case 2: System.out.println( Winter );! case 4:! case 5: System.out.println( Spring );! case 7:! case 8: System.out.println( Summer );! case 10:! case 11: System.out.println( Fall );! default: System.out.println( Ignored );! }!!!

Omitting the break! String season;! Scanner stdin = new Scanner(System.in);! int month = stdin.nextint();! switch (month) {! case 12: System.out.print( Solstice );! case 1:! case 2: System.out.println( Winter );! case 3: System.out.print( Equinox );! case 4:! case 5: System.out.println( Spring );! case 6: System.out.println( Solstice );! case 7:! case 8: System.out.println( Summer );! case 9: System.out.print( Equinox );! case 10:! case 11: System.out.println( Fall );! default: System.out.println( Ignored );! }!!!

Restrictions on Expression Type Early versions of Java restricted the switch expression to certain primitive types: int, byte, char and short! Also allowed the wrapper classes: Integer, Byte, Character and Short! Also allowed enumerated types Next version, Java SE7, will allow the String class

What if there s no case and no default? If no case matches the expression And no default is provided Execution continues with the first statement following the switch block

The? Conditional Operator

Conditional Operator? result = (condition)? value1 : value2 ; 1. Evaluates the boolean expression (condition) 2. If true, the result is value1 3. If false, the result is value2

Contrast? with the if Statement Imperative vs. Data Flow if (condition) result=value1; else result=value2; result = (condition)? value1 : value2;

Summary of if, if else,?, and switch!

Four Conditional Possibilities A conditional statement selects a course of action determined by a condition if (condition) statement;! if (condition) statement1; else statement2;! condition? value1 : value 2;! switch (condition) {case 1: case 2: default: }! Which one should I use?

if (condition) statement;! Condition is a boolean expression evaluating to true or false Condition determines whether to execute optional statement

if (condition) statement1; else statement2;! Condition is a boolean expression evaluating to true or false Condition selects statement1 or statement2 One of these two statements will always be executed!

condition? value1 : value 2 Condition is a boolean expression that selects either value1 or value2 Contrast with if..else which selects the next statement to execute The? conditional operator selects a value, not a statement result = condition? value1 : value2;! if (condition) result = value1; else result = value2;!

switch (condition) case Condition not restricted to a boolean expression. Often has an int value. Enumerations and Strings supported in recent Java versions. Selects one of many possible paths of execution Contrast with other conditionals whose boolean expressions limit their selection to two choices

do while!

Loops The while loop tests the continuation condition at the top of the loop, before executing statement(s) in the code block If the continuation condition fails in the first test, the code block is never executed Sometimes we want to go through the loop at least once

The Do While Loop The Do While Loop tests the continuation condition at the bottom of the loop Thus, the code block is always executed at least once

Example Do While Loop int i=20;! do {! System.out.println(i++);! } while (i<=10);! Similar to a while loop, but continuation test is at bottom Ensures the code block is executed at least once Not used a lot, but is occasionally handy

The for Loop

Loops Need to repeatedly execute a block of statement[s] Each time through the block is called an iteration or repetition Counter-Controlled repetition Sentinel-Controlled repetition

Review Sentinel-Controlled Repetition: Used when number of required iterations is unknown in advance Scanner stdin = new Scanner(System.in);! int x = stdin.nextint();! while (x>0) {! System.out.println(x*x);! x = stdin.nextint();! }! Sentinel variable controls repetition: x Continuation condition: x>0 Sentinel initialized by reading first value from stdin Sentinel update: Read from stdin inside the loop

Review Counter-Controlled Repetition: Used when number of required iterations is known in advance int i = 1;! while (i<=10) {! System.out.println(i);! i++;! }! Control variable: i Initial value of the control variable: 1 Continuation condition: i<=10 Control variable increment: 1

Counter-Controlled Repetition: The for Loop for(int i=1; i<=10; i++) {! }! System.out.println(i);! It s a shortcut for coding with a while loop Control (counter) variable: i Initial value of the control variable: 1 Continuation condition: i<=10 Control variable increment: 1

Counter-Controlled Repetition: Decrementing with a for Loop for(int i=10; i>=1; i--) {! System.out.println(i);! }! Control variable: i Initial value: 10 Increment/decrement: -1 Continuation condition: i>=1

Example: Interest double principal = 1000;! double interestrate = 0.05;! for(int i=1; i<=10; i++) {! }! principal += principal * interestrate;! System.out.println(principal);!