JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.

Slides:



Advertisements
Similar presentations
Repetition Statements Recitation – 02/20/2009 CS 180 Department of Computer Science, Purdue University.
Advertisements

Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Chapter 6 Repetition Asserting Java © Rick Mercer.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
LAB 10.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Introduction to Java. Main() Main method is where the program execution begins. There is only one main Displaying the results: System.out.println (“Hi.
CPS 2231 Computer Organization and Programming Instructor: Tian (Tina) Tian.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Truth and while Today 15 Minutes online time to finish the random/Swing programs. Truth tables: Ways to organize results of Boolean expressions. Note Taking:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING Switch Statement.
AP Java Java’s version of Repeat until.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Chapter 6 Repetition Asserting Java © Rick Mercer.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Selection Using IF THEN ELSE CASE Introducing Loops.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC111 Quick Revision.
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Repetition-Sentinel,Flag Loop/Do_While
Repetition.
Chapter 5: Control Structures II
TK1114 Computer Programming
Something about Java Introduction to Problem Solving and Programming 1.
Chapter 4 Control structures and Loops
Building Java Programs
Flow Control in Java.
Conditional Loops.
CSS161: Fundamentals of Computing
Truth tables: Ways to organize results of Boolean expressions.
CS18000: Problem Solving and Object-Oriented Programming
Control Statements Loops.
Truth tables: Ways to organize results of Boolean expressions.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Control Statements Loops.
Repetition Statements
Building Java Programs
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Presentation transcript:

JAVA Control Structures: Repetition

Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the use of boolean expressions Reinforce the use of Scanner for user input Reinforce the declaration and use of methods

3 Control Structures Control structures specify the ordering of the operations in the algorithm. There are three basic control structures: Sequence Selection Repetition

Motivation: Do something (anything!) times!

5 Repetitive Execution Repetition statements execute their statements repeatedly, often based on a boolean condition while (condition){ statement } condition False True A while loop executes a statement based on a boolean condition. Statement

Very Welcoming Program /** * Welcome repeatedly greets the user. * snelesen Fall 2011 */ import java.util.Scanner; public class Welcome { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print(“Please enter your name: “); String name = keyboard.next(); while( true ){ System.out.println(“Welcome “ + name + “!”); }

Sentinel-based input processing In an otherwise infinite loop, use break to exit: return will also cause loop execution to stop while( true ){ statements if (condition){ break; }

Personalized Welcome Program /** * Welcome greets each user until they quit */ import java.util.Scanner; public class Welcome { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); while( true ){ System.out.print(“Please enter your name (type “quit” to exit: “); String name = keyboard.next(); if (name.equals(“quit”){ break; } else { System.out.println(“Welcome “ + name + “!”); } } } }

Exercise Write a program that asks the user to input an unknown number of natural numbers, and computes their sum. Use a sentinel-based loop so that the user can enter -1 when they have entered all of their input. Input: natural numbers or -1 Output: display the sum of the numbers entered Algorithm: Repeat: 1. Ask user for input. 2. Check if input is -1 If input is -1, get out of loop If input is not -1, add input to accumulator Output accumulator.

Compute Sum...// documentation, class declaration, etc. public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int sum = 0; while( true ){ System.out.print(“Please enter a number (type “-1” to finish: “); int currentNumber= keyboard.nextInt(); if (currentNumber == -1){ break; } else { sum = sum + currentNumber; } } System.out.println(sum); } } // matches class declaration

11 while : Example System.out.print("Guess a number from 1-10: "); int number = -1; while (number != 7) { number = keyboard.nextInt(); } System.out.println("You guessed it!");

Example: Guess a random number... // documentation, import statement, class statement public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); // generate a random number between 0 and 100 int answer = (int)(Math.random() * 101); // The main guess loop int guess = -1; while( guess != answer ){ System.out.print(“Please enter your guess: “); guess = keyboard.nextInt(); if (guess > answer){ System.out.println(“Try lower”); } else if (guess < answer){ System.out.println(“Try higher”); } } System.out.println(“You got it!”); }

13 Example: Euclid’s Algorithm Given: Two positive natural numbers a & b, a >= b Return: Greatest common divisor Set remainder = the remainder of a divided by b Repeat these steps as long as remainder is not 0 Set a = b and b = remainder Set remainder = the remainder of a divided by b Go on to the next repetition Return b

Greatest Common Divisor int gcd (int a, int b){ int remainder = a % b; while( remainder != 0 ){ a = b; b = remainder; remainder = a % b; } return b; }

Common Forms int counter = 0; while( counter < 10 ){ System.out.print(“Welcome!“); counter = counter + 1; } int sum = 0, counter = 1; while( counter <= 10 ){ sum = sum + counter; counter = counter + 1; }

16 Repetitive Execution for statement: Forever loop provides no details: for([initExpr] ; [condition] ; [incrementExpr]){ statements } for( ; ; ){ statements } optional detail

17 General form of for for( [initExpr] ; [condition] ; [incrementExpr]){ statements } InitExpr LoopCond Statement IncrExpr F T optional detail

for loops int counter = 0; while( counter < 10 ){ System.out.print(“Welcome!“); counter = counter + 1; } int sum = 0, counter = 1; while( counter < 10 ){ sum = sum + counter; counter = counter + 1; } for (int counter = 0 ; counter < 10 ; counter++){ System.out.print(“Welcome!“); } int sum = 0; for ( int counter = 1; counter < 10 ; counter++){ sum = sum + counter; }

Exercise: Conversion Table Write a method that displays the following table: MilesKilometers

Exercise Write a program that displays all the numbers from 100 to 200, ten per line, that are divisible by 5 or 6, but not both.

21 Repetition: Nested for Loops for (initExpr 1 ; loopCond 1 ; incrExpr 1 ) for (initExpr 2 ; loopCond 2 ; incrExpr 2 ) Statement InitExpr 1 LoopCond 1 IncrExpr 1 F T Loops can be nested as well. InitExpr 2 LoopCond 2 Statement IncrExpr 2 F T

Example: Triangle of stars 22 for( int row = 0; row < 10; row++){ for (int column = 0; column < row; column++){ System.out.print(“*”); } System.out.print(“\n”); }