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

Similar documents
C++ Programming: From Problem Analysis to Program Design, Third Edition

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

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

Chapter 5: Control Structures II (Repetition)

Why Is Repetition Needed?

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 4: Control structures. Repetition

REPETITION CONTROL STRUCTURE LOGO

Chapter 4: Control structures

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

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Control Structures II. Repetition (Loops)

Loops / Repetition Statements

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

CompSci 125 Lecture 11

Repetition Structures

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

STUDENT LESSON A12 Iterations

Introduction. C provides two styles of flow control:

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

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

Lecture 7 Tao Wang 1

Loops (while and for)

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

CS 112 Introduction to Programming

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

Repetition, Looping. While Loop

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

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

Repetition, Looping CS101

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

Example: Monte Carlo Simulation 1

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

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

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Chapter 4: Control Structures I

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

CS 106 Introduction to Computer Science I

Computer Programming I - Unit 5 Lecture page 1 of 14

ECE 122. Engineering Problem Solving with Java

Control Statements: Part 1

Introduction to the Java Basics: Control Flow Statements

Recitation: Loop Jul 7, 2008

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

CS110D: PROGRAMMING LANGUAGE I

Loops. CSE 114, Computer Science 1 Stony Brook University

CS112 Lecture: Loops

Principles of Computer Science I

Chapter Goals. Contents LOOPS

Chapter 4 C Program Control

Dept. of CSE, IIT KGP

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

Midterm Review Session

Building Java Programs

Control Statements. Musa M. Ameen Computer Engineering Dept.

CS112 Lecture: Repetition Statements

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Full file at

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

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

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

Java Coding 3. Over & over again!

Controls Structure for Repetition

CS 106 Introduction to Computer Science I

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Building Java Programs

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

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

Building Java Programs

Information Science 1

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

! 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

COMP 202 Java in one week

Arithmetic Compound Assignment Operators

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Iteration statements - Loops

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

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

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

CS 112 Introduction to Programming

Programming for Experimental Research. Flow Control

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

Flow of Control: Loops. Chapter 4

Loops / Repetition Statements

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

switch-case Statements

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

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

204111: Computer and Programming

Repetition. Chapter 6

Repetition. Chapter 6

Repetition and Loop Statements Chapter 5

Control Structures in Java if-else and switch

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

Transcription:

Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOFcontrolled repetition structures Examine break and continue statements Discover how to form and use nested control structures Java Programming: Program Design Including Data Structures 2 Why Is Repetition Needed? Many situations require the same statement to be executed several times Example: Finding average grades for students in a class Java Programming: Program Design Including Data Structures 3 1

The while Looping (Repetition) Structure Syntax: while (expression) statement Expression is always true in an infinite loop Statements must change value of expression to false Java Programming: Program Design Including Data Structures 4 The while Looping (Repetition) Example 5-1 i = 0; //Line 1 while (i <= 20) //Line 2 Systemoutprint(i + " "); //Line 3 i = i + 5; //Line 4 Systemoutprintln(); //Line 5 Output 0 5 10 15 20 Java Programming: Program Design Including Data Structures 5 The while Looping (Repetition) while loops are written in the following form: //initialize the loop control variable(s) while (expression) //expression tests control //variable //update the loop control variable(s) Java Programming: Program Design Including Data Structures 6 2

Counter-Controlled while Loop Used when exact number of entry pieces is known General form: int N = //value input by user or specified //in program int counter = 0; while (counter < N) counter++; Java Programming: Program Design Including Data Structures 7 Sentinel-Controlled while Loop Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known General form: Input the first data item into variable; while (variable!= sentinel) input a data item into variable; Java Programming: Program Design Including Data Structures 8 Flag-Controlled while Loop Boolean value used to control loop General form: boolean found = false; while (!found) if (expression) found = true; Java Programming: Program Design Including Data Structures 9 3

EOF (End of File)-Controlled while Loop Used when input is from files Sentinel value is not always appropriate In an EOF-controlled while loop that uses the Scanner object console to input data, console acts at the loop control variable Java Programming: Program Design Including Data Structures 10 EOF (End of File)-Controlled while Loop (continued) The method hasnext, of the class Scanner, returns true if there is an input in the input stream; otherwise, it returns false The expression consolehasnext() acts as the loop condition Expressions such as consolenextint() update the value of the loop condition Java Programming: Program Design Including Data Structures 11 EOF-Controlled while Loop (continued) General form of the EOF-controlled while loop that uses the Scanner object console to input data: while (consolehasnext()) //Get the next input and store in an //appropriate variable //Process data Java Programming: Program Design Including Data Structures 12 4

EOF-Controlled while Loop (continued) Suppose that infile is a Scanner object initialized to the input file In this case, the EOFcontrolled while loop takes the following form: while (infilehasnext()) //Get the next input and store in an //appropriate variable //Process data Java Programming: Program Design Including Data Structures 13 Programming Example: Checking Account Balance Input file: Customer s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: Account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals Java Programming: Program Design Including Data Structures 14 Programming Example: Checking Account Balance (continued) Solution: Read data EOF-controlled loop switch structure of transaction types Determine action (add to balance or subtract from balance depending on transaction type) Java Programming: Program Design Including Data Structures 15 5

Programming Example: Fibonacci Number Fibonacci formula for any Fibonacci sequence: a n = a n-1 + a n-2 Input: First two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n) int previous1 = Fibonacci number 1 int previous2 = Fibonacci number 2 int nthfibonacci = Position of nth Fibonacci number Output: nth Fibonacci number Java Programming: Program Design Including Data Structures 16 Programming Example: Fibonacci Number (Solution) if (nthfibonacci == 1) current = previous1; else if (nthfibonacci == 2) current = previous2; else counter = 3; while (counter <= nthfibonacci) current = previous2 + previous1; previous1 = previous2; previous2 = current; counter++; Java Programming: Program Design Including Data Structures 17 The for Looping (Repetition) Structure Specialized form of while loop Simplifies the writing of count-controlled loops Syntax: for (initial statement; loop condition; update statement) statement Java Programming: Program Design Including Data Structures 18 6

The for Looping (Repetition) Execution: Initial statement executes Loop condition is evaluated If loop condition evaluates to true, execute for loop statement and execute update statement Repeat until loop condition is false Java Programming: Program Design Including Data Structures 19 The for Looping (Repetition) Java Programming: Program Design Including Data Structures 20 The for Looping (Repetition) Example 5-8 The following for loop prints the first 10 nonnegative integers: for (i = 0; i < 10; i++) Systemoutprint(i + " "); Systemoutprintln(); Java Programming: Program Design Including Data Structures 21 7

The for Looping (Repetition) Example 5-9 1 The following for loop outputs the word Hello and a star (on separate lines) five times: for (i = 1; i <= 5; i++) Systemoutprintln("Hello"); Systemoutprintln("*"); Java Programming: Program Design Including Data Structures 22 The for Looping (Repetition) 2 The following for loop outputs the word Hello five times and the star only once: for (i = 1; i <= 5; i++) Systemoutprintln("Hello"); Systemoutprintln("*"); Java Programming: Program Design Including Data Structures 23 The for Looping (Repetition) Does not execute if initial condition is false Update expression changes value of loop control variable, eventually making it false If loop condition is always true, result is an infinite loop Java Programming: Program Design Including Data Structures 24 8

The for Looping (Repetition) Infinite loop can be specified by omitting all three control statements If loop condition is omitted, it is assumed to be true for statement ending in semicolon is empty Java Programming: Program Design Including Data Structures 25 Programming Example: Classify Numbers Input: N integers (positive, negative, and zeros) int N = 20; //N easily modified Output: Number of 0s, number of even integers, number of odd integers Java Programming: Program Design Including Data Structures 26 Programming Example: Classify Numbers (Solution) for (counter = 1; counter <= N; counter++) number = consolenextint(); Systemoutprint(number + " "); switch (number % 2) case 0: evens++; if (number == 0) zeros++; break; case 1: case -1: odds++; //end switch //end for loop Java Programming: Program Design Including Data Structures 27 9

The do while Loop (Repetition) Structure Syntax: do statement while (expression); Statements are executed before expression Statements are executed at least once and then continued if expression is true Java Programming: Program Design Including Data Structures 28 do while Loop (Post-Test Loop) Java Programming: Program Design Including Data Structures 29 break Statements Used to exit early from a loop Used to skip remainder of switch structure Can be placed within if statement of a loop If condition is met, loop is exited immediately Java Programming: Program Design Including Data Structures 30 10

continue Statements Used in while, for, and dowhile structures When executed in a loop: Remaining statements in the loop are skipped Proceeds with the next iteration of the loop When executed in a while/do while structure, expression is evaluated after continue In a for structure, the update statement is executed after continue; the loop condition then executes Java Programming: Program Design Including Data Structures 31 Nested Control Structures Provides new power, subtlety, and complexity if, if else, and switch structures can be placed within while loops for loops can be found within other for loops Java Programming: Program Design Including Data Structures 32 Nested Control Structures (Example) for (int i = 1; i <= 5; i++) for (int j = 1; j <= i; j++) Systemoutprint(" *"); Systemoutprintln(); Output: * ** *** **** ***** Java Programming: Program Design Including Data Structures 33 11

Chapter Summary Looping mechanisms: Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop EOF-controlled while loop for loop do while loop break statement continue statement Nested control structures Java Programming: Program Design Including Data Structures 34 12