CS1004: Intro to CS in Java, Spring 2005

Similar documents
ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Conditionals and Loops

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Java Flow of Control

Chapter 4: Conditionals and Loops

Program Planning, Data Comparisons, Strings

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

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

Chapter 4: Conditionals and Loops

Chapter 4: Conditionals and Loops

More Programming Constructs -- Introduction

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

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

CMPT 125: Lecture 4 Conditionals and Loops

Lab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.

Loops / Repetition Statements

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

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

CS111: PROGRAMMING LANGUAGE II

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

Repetition Structures

Conditional Programming

printf( Please enter another number: ); scanf( %d, &num2);

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

ECE 122. Engineering Problem Solving with Java

Logical Operators and switch

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Flow of Control. Chapter 3. Chapter 3 1

STUDENT LESSON A12 Iterations

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Information Science 1

Full file at

Computer Programming I - Unit 5 Lecture page 1 of 14

BRANCHING if-else statements

CS Final Exam Review Suggestions - Spring 2014

Control Structures in Java if-else and switch

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

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

REPETITION CONTROL STRUCTURE LOGO

Looping. Arizona State University 1

CompSci 125 Lecture 11

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

1007 Imperative Programming Part II

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

Information Science 1

The Basic Parts of Java

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

CIS 110: Introduction to Computer Programming

Control Statements Loops

Loops / Repetition Statements

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

Why Is Repetition Needed?

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Flow of Control: Loops. Chapter 4

CS1004: Intro to CS in Java, Spring 2005

Chapter 3. Selections

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Midterm Review Topics Java Basics and Structure Variables Branching Loops Methods Arrays. Midterm Review Kage Weiss Lab 001 TA, SPR 17

Loops. CSE 114, Computer Science 1 Stony Brook University

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

COMP Primitive and Class Types. Yi Hong May 14, 2015

McGill University School of Computer Science COMP-202A Introduction to Computing 1

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

Flow of Control: Loops

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Accelerating Information Technology Innovation

Problem Solving With Loops

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

Controls Structure for Repetition

LESSON 3 CONTROL STRUCTURES

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output

CS Final Exam Review Suggestions - Fall 2017

Exam 1. CSC 121 Spring Lecturer: Howard Rosenthal. March 1, 2017

CT 229 Java Syntax Continued

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Getting started with Java

Chapter Goals. Contents LOOPS

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

CS 115 Lecture 8. Selection: the if statement. Neil Moore

CIS 130 Exam #2 Review Suggestions

Scope of this lecture. Repetition For loops While loops

Control Structures in Java if-else and switch

APCS Semester #1 Final Exam Practice Problems

Chapter 4 C Program Control

Darrell Bethea May 25, 2011

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

CS Exam 2 Study Suggestions

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

Repetition, Looping. While Loop

Flow of Control: Loops. Objectives. Java Loop Statements: Outline 6/27/2014. Chapter 4

CS 177 Week 5 Recitation Slides. Loops

Computing Science 114 Solutions to Midterm Examination Tuesday October 19, In Questions 1 20, Circle EXACTLY ONE choice as the best answer

Conditionals, Loops, and Style

Flow of Control: Loops

Java Control Statements

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Transcription:

CS1004: Intro to CS in Java, Spring 2005 Lecture #16: Java conditionals/loops, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Midterms returned now Weird distribution Mean: 35.4 ± 8.4 What does this mean? In-class extra credit HW#3 returned Thurs. HW#4 out Frequency Histogram 25 20 15 10 5 0 11.5 15.77777778 20.05555556 24.33333333 28.61111111 32.88888889 37.16666667 Bin 41.44444444 45.72222222 More The Conditional Operator, redux (Another) Example: System.out.println ("Your change is " + count + ((count == 1)? "Dime" : "Dimes")); If count equals 1, then "Dime" is printed If count is anything other than 1, then "Dimes" is printed 1

The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches The switch Statement (II) The general syntax of a switch statement is: switch and case are reserved words switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... If expression matches value2, control jumps to here switch and break Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Biggest common bug with switch, and a reason why I use it sparingly 2

switch Example An example of a switch statement: switch (option) { case 'A': acount++; break; case 'B': bcount++; break; case 'C': ccount++; break; switch and default case A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch What can you switch on? The expression of a switch statement must result in an integral type,, meaning an integer (byte, short, int, long) ) or a char It cannot be a boolean value or a floating point value (float( or double) The implicit boolean condition in a switch statement is equality (==, not.equals()) Common for things like menu systems ( Enter( one of the above 5 options ) 3

Comparing Data When comparing data using boolean expressions, it's important to understand the nuances of certain data types We ve talked about these, but now let s formalize it Comparing Float Values You should rarely use the equality operator (==( ==) when comparing two floating point values (float or double) Two floating point values are equal only if their underlying binary representations match exactly Computations often result in slight differences that may be irrelevant In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal Comparing Float Values (II) To determine the equality of two floats, you may want to use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as 0.000001 4

Comparing Characters As we've discussed, Java character data is based on the Unicode character set Unicode establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering For example, the character '+' is less than the character 'J'' because it comes before it in the Unicode character set Appendix C provides an overview of Unicode Comparing Characters (II) In Unicode, the digit characters (0-9) are contiguous and in order Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order Characters 0 9 A Z a z Unicode Values 48 through 57 65 through 90 97 through 122 String equality Remember that in Java a character string is an object The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); 5

String inequalities We cannot use the relational operators to compare strings The String class contains a method called compareto to determine if one string comes before another A call to name1.compareto(name2) returns zero if name1 and name2 are equal (contain the same characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2 compareto example if (name1.compareto(name2) < 0) System.out.println (name1 + "comes first"); else if (name1.compareto(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first"); Because comparing characters and strings is based on a character set, it is called a lexicographic ordering Lexicographic Ordering Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase" 6

Comparing Objects The == operator can be applied to objects, as we mentioned before The equals method is also defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator It has been redefined in the String class to compare the characters in the two strings When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate Repetition Statements Repetition statements allow us to execute a statement multiple times, often referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: while, do,, and for All are equivalent, but some are easier to use for certain cases The while Statement A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false 7

Logic of a while Loop condition evaluated true false statement Example An example of a while statement: int count = 1; while(count < 5) { System.out.println(count); count++; If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times More complex example Maintain a running sum A sentinel value is a special input value that represents the end of input Input validation While the user types an invalid value, reject and wait for a valid value. Example: calculate mean of exams Similar to if statements, while statements can be nested as well 8

Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop,, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally Infinite Loops An example of an infinite loop: int count = 1; while(count <= 25) { System.out.println(count); count = count - 1; This loop will continue executing until interrupted or until an underflow error occurs Nested Loops How many times will the string "Here" be printed? count1 = 1; while(count1 <= 10) { count2 = 1; while(count2 <= 20) { System.out.println("Here"); count2++; count1++; 9

break, version 2 We saw break in the context of switch,, but it can be used with while (and other loops) as well; for example, while(true) ) { if(i > 10) break; else i++; What is this code equivalent to? Generally, you don t t use break, but it s s useful to have, especially if the while loop is very complex If you have nested loops, break only breaks out of the most immediate loop, not all of them return can be used to break out of a bunch of loops, but avoid The do Statement A do statement has the following syntax: do { statement; while(condition); The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false The do Statement An example of a do loop: int count = 0; do { count++; System.out.println(count); while (count < 5); The body of a do loop executes at least once What s s the result of this code fragment? do is particularly useful for interactive repetition 10

Comparing while and do The while Loop The do Loop condition evaluated true statement true statement false condition evaluated false The for Statement A for statement has the following syntax: The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration Logic of a for loop initialization condition evaluated true false statement increment 11

The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while(condition) { statement; increment; The for Statement An example of a for loop: for (int count=1; count < 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times 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 12

The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed Next time Finish for Start building more complex examples with loop constructs Think about how algorithms are created using conditions and loops 13