Combined Assignment Operators. Flow of Control. Increment Decrement Operators. Operators Precedence (Highest to Lowest) Slide Set 05: Java Loops

Similar documents
Control Structures. Repetition (Loop) Structure. Repetition (Loop) Structure. Repetition (Loop) Structure. CS225: Slide Set 8: C++ Loop Structure

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Midterm Examination (MTA)

STUDENT LESSON A12 Iterations

Flow of Control. Relational Operators. Operators Review. Order of Operations

JAVA OPERATORS GENERAL

Question: Total Points: Score:

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CompSci 125 Lecture 11

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

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

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

Chapter 3. Selections

Question: Total Points: Score:

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

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

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

Full file at

Java Coding 3. Over & over again!

Question: Total Points: Score:

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

CSC 1051 Data Structures and Algorithms I

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Example: Monte Carlo Simulation 1

Introduction to Java & Fundamental Data Types

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

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

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Building Java Programs

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

Repetition. Chapter 6

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

CMPT 125: Lecture 4 Conditionals and Loops

Repetition. Chapter 6

Programming with Java

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Chapter 4: Control Structures I

Loops and Expression Types

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

Chapter 3: Operators, Expressions and Type Conversion

Unit 1 Lesson 4. Introduction to Control Statements

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

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

CSC 1051 Data Structures and Algorithms I

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Question: Total Points: Score:

Repetition CSC 121 Fall 2014 Howard Rosenthal

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

4 WORKING WITH DATA TYPES AND OPERATIONS

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

Top-Down Program Development

Introduction to Programming Using Java (98-388)

Program Control Flow

Program Control Flow

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

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

CSC 1214: Object-Oriented Programming

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

CS141 Programming Assignment #6

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

Chapter 2. Elementary Programming

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

CS111: PROGRAMMING LANGUAGE II

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

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

Condensed Java. 12-Oct-15

Introduction to Computer Science Midterm 3 Fall, Points

Lesson 7 Part 2 Flags

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

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

Mr. Monroe s Guide to Mastering Java Syntax

Introduction to Computer Programming

Building Java Programs

Dept. of CSE, IIT KGP

Repetition, Looping. While Loop

Chapter 5 Lab Methods

Java Basic Programming Constructs

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Control Structures: if and while A C S L E C T U R E 4

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Object Oriented Programming. Java-Lecture 1

Prof. Navrati Saxena TA: Rochak Sachan

Review for Test 1 (Chapter 1-5)

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

Exam 2, Version 2. For the following code, mark True or False for statements 1.8 to 1.10.

AP COMPUTER SCIENCE A

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

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

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

Selections. CSE 114, Computer Science 1 Stony Brook University

Chapter 4 Control Structures

A Look Back at Arithmetic Operators: the Increment and Decrement

Transcription:

Flow of control Flow of Control Program instruction execution sequence Sequential Control Structure Selection (Branching) Control Structure Repetition (Loop) Control Structure Operator Usage Relational and Logical Operators Compound assignment Increment and decrement while loops do while loops for loops Copyright 2012 R.M. Laurie 1 Combined Assignment Operators Addition Assignment Operator += na += 5; // na = na + 5 Concatenation Assignment Operator += sresults += "Done"; // sr = sr + "Done"; Subraction Assignment Operator na -= 8; // na = na - 8 -= Muliplication Assignment Operator na *= 2; // na = na * 2 *= Division Assignment Operator na /= 4; // na = na / 4 /= Remainder (modulus) Assignment Operator na %= 10; // na = na % 10 %= More Examples dtotal += dentry; sresults += "\ntotal = $" + dtotal; Copyright 2012 R.M. Laurie 2 Increment Decrement Operators Post-Increment Operator ncnt++ ncnt++; // ncnt, ncnt = ncnt + 1 Pre-Increment Operator ++ncnt ++ncnt; // ncnt = ncnt + 1 Post-Decrement Operator ncnt-- ncnt--; // ncnt, ncnt = ncnt - 1 Pre-Increment Operator --ncnt --ncnt; // ncnt = ncnt 1 Example int na = 5; System.out.writeln(nA++); // Displays 5, na = 6 System.out.writeln(--nA); // Displays 5, na = 5 System.out.writeln(++nA); // Displays 6, na = 6 System.out.writeln(nA--); // Displays 6, na = 5 Copyright 2012 R.M. Laurie 3 Operators Precedence (Highest to Lowest) ( ) Defines order of operation - ++ -- Minus, increment, decrement (unary) (int) (double) Type cast operators! Logical NOT (unary) * / % Multiply, Division, Remainder + - Addition&Concatenation, Subtraction < <= > >= Comparison ==!= Equality && Logical AND OR = += -= *= /= %= Compound Assignment Copyright 2012 R.M. Laurie 4 Copyright 2012 R.M. Laurie 1

Repetition (Loop) Structure Control structure used to repeat a sequence of instructions in a loop. Assertion then executes the loop section Assertion then exits the loop section less loop in a program is dangerous logic error because stuck in loop Initialize Counter Check Counter er Copyright 2012 R.M. Laurie 5 while statement loop control Contents of loop executed repeatedly while(assertion) is true Loop terminated when while(assertion) is false Counter-Controlled Repetition Structure Initialize a counter to count loops Increment or decrement counter while(assertion) checks for total loops reached Sentinel-Controlled Repetition Structure while(assertion) checks for a sentinel termination value Copyright 2012 R.M. Laurie 6 Counter Controlled Repetition Structure Score 1 = 78 Score 2 = 82 Score 3 = 87 Score 4 = 93 Score 5 = 86 Average = 85 2. public class WhileIntro 3. 6. int nscore, n, n; 7. String sentry; 8. while(n) 9. 10. sentry=joptionpane.showinputdialog( 11. "Enter Score "+ncount+":"); 12. nscore = Integer.parseInt(sEntry); 13. nsum += nscore; 14. System.out.println("Score " 15. + ncount + " = " + nscore); 16. n; 17. 18. System.out.println("\nAverage = " 19. + nsum/5); 20. 21. Copyright 2012 R.M. Laurie 7 Sentinel Controlled Repetition Structure 2. public class WhileSentinal 3. 6. int ncount = 0, nscore, n; 7. String sentry; 8. sentry=joptionpane.showinputdialog( 9. "Enter Score " + (ncount + 1) 10. + ": (-1 to exit)"); 11. nscore = Integer.parseInt(sEntry); 12. while(nscore >= 0) 13. 14. nsum += nscore; 15. n; 16. System.out.println("Score " 17. + ncount + " = " + nscore); 18. sentry=joptionpane.showinputdialog( 19. "Enter Score "+ (ncount + 1) 20. + ": (-1 to exit)"); 21. nscore = Integer.parseInt(sEntry); 22. 23. if(ncount > 0) 24. System.out.printf( Display: None Entered 25. "\naverage =%6.2f\n%d scores\n", 26. + (double)nsum/ncount, ncount); 27. else 28. System.out.println("No Scores Entered"); 29. 30. Score 1 = 78 Score 2 = 82 Score 3 = 87 Score 4 = 93 Score 5 = 86 Average = 85.20 5 scores Count >0 Avg = Sum/Count Count = 0 Score >= 0 Copyright 2012 R.M. Laurie 8 Copyright 2012 R.M. Laurie 2

break; continue; commands To exit a loop from within the loop use if(assertion) break; To return to the beginning of the loop without further processing use if(assertion) continue; Loop assertion can be set to true if relying on break to exit loop Assertion? Score=NaN Score < 0 Exit Copyright 2012 R.M. Laurie 9 Sentinel Controlled Repetition Structure 2. public class WhileBreak 3. 6. int ncount = 0, nscore, n; 7. char cchr0; 8. String sentry; 9. while(true) 10. 11. sentry=joptionpane.showinputdialog( 12. "Enter Score "+ (ncount + 1) 13. + ": (Q to quit)"); 14. cchr0 = sentry.charat(0); 15. if(cchr0 == 'q' cchr0 == 'Q') break; 16. if(!character.isdigit(cchr0)) continue; 17. nscore = Integer.parseInt(sEntry); Score 1 = 45 Score 2 = 78 Score 3 = 67 Score 4 = 67 Average = 64.25 For 4 scores Count >0 Count = 0 Chr0 ='q' 18. nsum += nscore; Display: 19. n; None Entered 20. System.out.println("Score " 21. + ncount + " = " + nscore); 22. Avg = Sum/Count 23. if(ncount > 0) 24. System.out.printf( 25. 26. "\naverage =%6.2f\nFor %d scores\n", + (double)nsum/ncount, ncount); 27. else 28. System.out.println("No Scores Entered"); 29. 30. // Exception Handling covered in Chapter 13 Copyright 2012 R.M. Laurie 10 true Chr0=digit Score!=0 Calculate Avg do - while Loop Control Loop structure that guarantees the loop body is executed once Assertion tested bottom of loop Don t forget the semicolon for while(assertion); 2. public class DoWhile 3. 6. int ncount = 0, nscore, n; 7. Scanner kbdinput = new Scanner(System.in); 8. do 9. 10. n; 11. System.out.printf( 12. "Enter Score %2d (0 to quit):", ncount); 13. nscore = kbdinput.nextint(); 14. nsum += nscore; 15. while(nscore!= 0); 16. System.out.printf( 17. "\naverage =%6.2f\nFor %d scores\n", 18. + (double)nsum/--ncount, ncount); 19. 20. Copyright 2012 R.M. Laurie 11 2. public class WhileYN_Word Filtered Input Application 3. 6. String sentry = new String(""); 7. Scanner keyentry = new Scanner(System.in); 8. while(true) 9. 10. System.out.println("Do you like Java Programming? (yes or no)"); 11. sentry = keyentry.nextline(); 12. if(sentry.equals("yes")) 13. 14. System.out.println("I am glad you like Java Programming" ); 15. break; 16. 17. else if(sentry.equals("no")) 18. 19. System.out.println("You will like it if you read the book" ); 20. break; 21. 22. else 23. System.out.println("Please enter yes or no" ); 24. 25. keyentry.close(); 26. 27. Copyright 2012 R.M. Laurie 3

Filtered Input Application: do-while 2. public class DoWhileYN_Word 3. 6. String sentry = new String(""); Do you like Java Programming? (yes or no) y Please enter yes or no Do you like Java Programming? (yes or no) yes I am glad you like Java Programming 7. Scanner keyentry = new Scanner(System.in); 8. do 9. 10. System.out.println("Do you like Java Programming? (yes or no)"); 11. sentry = keyentry.nextline(); 12. if(sentry.equals("yes")) 13. System.out.println("I am glad you like Java Programming"); 14. else if(sentry.equals("no")) 15. System.out.println("You will like it if you read the book"); 16. else 17. System.out.println("Please enter yes or no" ); 18. while(!( sentry.equals("yes") sentry.equals("no") ) ); 19. keyentry.close(); 20. 21. Copyright 2012 R.M. Laurie 13 for Statement Loop Control for statement is best for counter controlled loops for statement includes Initialize, assertion check, Initialize and increment/decrement Counter Check Counter Increment Counter Enter Score 1: 76 Enter Score 2: 82 Enter Score 3: 95 Enter Score 4: 67 Enter Score 5: 77 Average = 79.4 import java.util.scanner; public class ForIntro public static void main(string[] args) final int SCORE_QTY = 5; int n; Scanner keyentry = new Scanner(System.in); for(int n; ncount <= SCORE_QTY; n) System.out.print("Enter Score " + ncount + ":"); nsum += keyentry.nextint(); System.out.println("\nAverage = " + (double)nsum/score_qty ); Copyright 2012 R.M. Laurie 14 Number, Square, Cube - for Example Nested for loop 1. public class ForExample 2. 3. public static void main(string args[]) 4. 5. final int MAX = 20; 6. System.out.println("Number Square Cube"); 7. System.out.println("------ ------ ------"); 8. for(int ni=1; ni <= MAX; ni++) 9. 10. System.out.printf(" %3d %6d %6d\n", 11. ni, ni*ni, ni*ni*ni); 12. 13. 14. Number Square Cube ------ ------ ------ 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331 12 144 1728 13 169 2197 14 196 2744 15 225 3375 16 256 4096 17 289 4913 18 324 5832 19 361 6859 20 400 8000 Copyright 2012 R.M. Laurie 15 public class ForNested public static void main(string args[]) final int RBGN = 1, REND = 15, RINC = 1; final int CBGN = 5, CEND = 20, CINC = 5; System.out.print("MULTIPLICATION TABLE\n" + "\n "); for(int nk = CBGN; nk <= CEND; nk += CINC) System.out.printf("%5d ", nk); System.out.print("\n"); for(int ni = RBGN; ni <= REND; ni += RINC) System.out.printf("Row%3d:", ni); for(int nj = CBGN; nj <= CEND; nj += CINC) System.out.printf("%5d ", ni*nj); System.out.printf("%n"); MULTIPLICATION TABLE 5 10 15 20 Row 1: 5 10 15 20 Row 2: 10 20 30 40 Row 3: 15 30 45 60 Row 4: 20 40 60 80 Row 5: 25 50 75 100 Row 6: 30 60 90 120 Row 7: 35 70 105 140 Row 8: 40 80 120 160 Row 9: 45 90 135 180 Row 10: 50 100 150 200 Row 11: 55 110 165 220 Row 12: 60 120 180 240 Row 13: 65 130 195 260 Row 14: 70 140 210 280 Row 15: 75 150 225 300 Copyright 2012 R.M. Laurie 16 Copyright 2012 R.M. Laurie 4

Greatest Common Divisor 2. // GCD = Greatest Common Divisor Program 3. // Similar to p132 but uses for loop 4. public class GCD 6. public static void main(string[] args) 7. 8. Scanner kbdinput = new Scanner(System.in); 9. System.out.print("Enter the first integer: "); 10. int nnum1 = kbdinput.nextint(); 11. System.out.print("Enter the second integer: "); 12. int nnum2 = kbdinput.nextint(); 13. int ngcd = 1; 14. for(int ni = 2; ni <= nnum1 && ni <= nnum2; ni++) 1 16. if(nnum1 % ni == 0 && nnum2 % ni == 0) 17. ngcd = ni; 18. 19. System.out.println("The greatest common divisor for " 20. + nnum1 + " and " + nnum2 + " is " + ngcd); 21. 22. Copyright 2012 R.M. Laurie 17 2. // Prime Numbers Program 3. // Similar to p138 except uses nested for loops 4. public class PrimeNumbers 6. public static void main(string[] args) 7. 8. Scanner kbdinput = new Scanner(System.in); 9. System.out.print("Enter the total prime numbers to " 10. + "calculate\nand primes to display per line: "); 11. int nqtyprime = kbdinput.nextint(); 12. int nqtyline = kbdinput.nextint(); 13. System.out.println("The first " + nqtyprime 14. + " prime numbers are:\n"); 15. for(int ni = 0, nnum = 2; ni < nqtyprime; nnum++) 16. 17. boolean bprime = true; 18. for(int ndiv = 2; ndiv <= nnum / 2; ndiv++) 19. 20. if(nnum % ndiv == 0 ) 21. 22. bprime = false; 23. break; 24. 25. 26. if(bprime) 27. 28. ni++; 29. if(ni % nqtyline == 0) 30. System.out.printf("%7d\n", nnum); 31. else 32. System.out.printf("%7d,", nnum); 33. 34. 35. 36. Prime Numbers 1 Enter the total prime numbers to calculate and primes to display per line: 30 5 The first 30 prime numbers are: 2, 3, 5, 7, 11 13, 17, 19, 23, 29 31, 37, 41, 43, 47 53, 59, 61, 67, 71 73, 79, 83, 89, 97 101, 103, 107, 109, 113 2. // Prime Method Program 3. public class PrimeMethod 5. Scanner kbdinput = new Scanner(System.in); 6. System.out.print("Enter the total prime numbers to " 7. + "calculate\nand primes to display per line: "); 8. int nqtyprime = kbdinput.nextint(); 9. int nqtyline = kbdinput.nextint(); 10. System.out.println("The first " + nqtyprime 11. + " prime numbers are:\n"); 12. for(int ni = 0, nnum = 2; ni < nqtyprime; nnum++) Prime Numbers 2 13. 14. if(isprime(nnum)) 1 16. ni++; 17. printprime(nnum, ni, nqtyline); 18. 19. 20. 21. public static boolean isprime(int nnumber) 22. for(int ndiv = 2; ndiv <= nnumber / 2; ndiv++) 23. if(nnumber % ndiv == 0 ) 24. return false; 25. return true; 26. 27. private static void printprime(int nprime, int ncnt, int nline) 28. if(ncnt % nline == 0) 29. System.out.printf("%7d\n", nprime); 30. else 31. System.out.printf("%7d,", nprime); 32. 33. Enter the total prime numbers to calculate and primes to display per line: 30 5 The first 30 prime numbers are: 2, 3, 5, 7, 11 13, 17, 19, 23, 29 31, 37, 41, 43, 47 53, 59, 61, 67, 71 73, 79, 83, 89, 97 101, 103, 107, 109, 113 Homework 2: Test Score Loop 1. For this program you will enter a series of test scores with a possible range of scores between 0 and 100. The number of scores is not fixed and can be different for each run of the program. 2. After all scores are entered the program will display the high score, the average score, and the low score for the entered series of scores. 3. You should go through the usual program design phase. However, you do not need to turn it in for this homework assignment. 4. Implement your program design using NotePad++ or Eclipse and name your file YourName_hw2.java 5. Compile using Java SE 6 JDK compiler and debug until all syntax errors are eliminated. Demonstrate your code runs without logic errors by running the program and enter your known test data. 6. Your instructor must verify the program works during the class. Please upload via WebTycho your YourName_hw2.java program source code file to the Homework 2 assignment folder 7. This program is due at the beginning of Class 2 - Week 4. Copyright 2012 R.M. Laurie 20 Copyright 2012 R.M. Laurie 5