Five-Minute Review 1.What are classes and objects? What is a class hierarchy? 2.What is an expression? A term? 3.What is a variable declaration? 4.What.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Nested for Statements The body of a control statement can contain other statements. Such statements are said to be nested. Many applications require nested.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Chapter 4—Statement Forms The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Statement Forms C H A P T E R 4 The statements.
Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements.
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Java Programming: From the Ground Up
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
CPS120: Introduction to Computer Science Decision Making in Programs.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
JavaScript, Fourth Edition
Chapter 4—Statement Forms The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Statement Forms C H A P T E R 4 The statements.
CSCI 161 Lecture 7 Martin van Bommel. Control Statements Statements that affect the sequence of execution of other statements Normal is sequential May.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
In the last lesson we discussed about: Casting Precedence The “=“ used as an assignment operator Made a calculate average program.
Chapter 7 Problem Solving with Loops
Decision Making and Branching (cont.)
Control Statements Eric Roberts CS 106A January 15, 2016.
Expressions Eric Roberts CS 106A January 13, 2016.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
COMP Loop Statements Yi Hong May 21, 2015.
CISC105 – General Computer Science Class 4 – 06/14/2006.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Control Statements Eric Roberts CS 106A January 15, 2010.
Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Eric Roberts and Jerry Cain
Five-Minute Review What are classes and objects? What is a class hierarchy? What is an expression? A term? What is a variable declaration? What is an assignment?
CS 106A, Lecture 4 Introduction to Java
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 4: Making Decisions.
Python: Control Structures
Chapter 5: Control Structures II
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Chapter 4: Making Decisions.
CS 106A, Lecture 6 Control Flow and Parameters
Looping.
Five-Minute Review What is a class hierarchy?
slides courtesy of Eric Roberts
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Chapter 4—Statement Forms
Presentation transcript:

Five-Minute Review 1.What are classes and objects? What is a class hierarchy? 2.What is an expression? A term? 3.What is a variable declaration? 4.What is an assignment? What is precedence? 5.What do you know about Booleans? 1

Programming – Lecture 4 Statement Forms (Chapter 4) Repeat N-Times Pattern Repeat-Until-Sentinel Pattern if/else ? : switch while, do while Loop-and-a-Half Pattern for Animation

Chapter 4—Statement Forms The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Statement Forms C H A P T E R 4 The statements was interesting but tough. —Mark Twain, The Adventures of Huckleberry Finn, Statement types in Java 4.2 Control statements and problem solving 4.3 The if statement 4.4 The switch statement 4.5 The while statement 4.6 The for statement

Statement Types Recall: Expressions, have type, are interested in value Recall: Classes, Methods, Statements Statements: units of execution, are interested in side effect Distinguish Expression statements Declaration statements Control flow statements Compound statements (blocks) 4

Expression Statements Assignment expressions aValue = ; Any use of ++ or -- aValue++; Method invocations System.out.println("Hello!"); Object creation expressions new Bicycle(); Note: the book defines simple statements as “expression ; ” instead of expression/declaration statements. However, declarations are not expressions, and not all expressions (such as “17”) lead to valid statements. 5

Statement Types in Java Programs in Java consist of a set of classes. Those classes contain methods, and each of those methods consists of a sequence of statements. Statements in Java fall into three basic types: –Simple statements (expression statements or declaration statements) –Compound statements –Control statements Compound statements (also called blocks) consist of a sequence of statements enclosed in curly braces. Control statements fall into two categories: –Conditional statements that specify some kind of test –Iterative statements that specify repetition

Control Statements and Problem Solving Before looking at the individual control statement forms in detail, it helps to look more holistically at a couple of programs that make use of common control patterns. The next few slides extend the Add2Integers program from Chapter 2 to create programs that add longer lists of integers. These slides illustrate three different strategies: –Adding new code to process each input value –Repeating the input cycle a predetermined number of times –Repeating the input cycle until the user enters a special sentinel value

if Statement if ( condition ) { statements to be executed if the condition is true } if ( condition ) { statements to be executed if the condition is true } else { statements to be executed if the condition is false } Cascading if 8

Dangling Else if (x > 0) if (doprint) println(“x positive”); else if (doprint) println(“x not positive”); If an if has an else clause, always use braces in if clause! 9

Choosing between if and if / else As is true with most programming constructs, there is no hard-and-fast rule that will tell you whether you need the basic if statement or the if / else form. The best general guideline is to think about the English description of the problem you are trying to solve. If that description contains the words else or otherwise, there is a good chance that the solution will use the else keyword. As an example, suppose that you wanted to change the AverageList program so that it didn’t include any zero values in the average. Here, you need a simple if statement that makes sure that the score is not equal to 0. public void run() { println("This program averages a list of numbers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; int count = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } double average = (double) total / count; println("The average is " + average + "."); } total += value; count++; if (value != 0) { } nonzero As is true with most programming constructs, there is no hard-and-fast rule that will tell you whether you need the basic if statement or the if / else form. The best general guideline is to think about the English description of the problem you are trying to solve. If that description contains the words else or otherwise, there is a good chance that the solution will use the else keyword. As an example, suppose that you wanted to change the AverageList program so that it didn’t include any zero values in the average. Here, you need a simple if statement that makes sure that the score is not equal to 0. If you also wanted to count the nonzero scores, you would need to add an else clause to increment a counter variable in the case that value was equal to 0.

Common Forms of the if Statement if ( condition ) statement Single line if statement if ( condition ) { statement... more statements... } Multiline if statement with curly braces if ( condition ) { statements true } else { statements false } if / else statement with curly braces if ( condition 1 ) { statements 1 } else if ( condition 2 ) { statements 2... more else / if conditions... } else { statements else } Cascading if statement The examples in the book use the if statement in the following forms:

?: Operator condition ? expression 1 : expression 2 12

switch Statement switch ( expression ) { case v 1 : statements to be executed if expression = v 1 break; case v 2 : statements to be executed if expression = v 2 break;... more case clauses if needed... default: statements to be executed if no values match break; } 13

public void run() { println("This program shows the number of days in a month."); int month = readInt("Enter numeric month (Jan=1): "); switch (month) { case 2: println("28 days (29 in leap years)"); break; case 4: case 6: case 9: case 11: println("30 days"); break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: println("31 days"); break; default: println("Illegal month number"); break; } 14

Add4Integers public class Add4Integers extends ConsoleProgram { public void run() { println("This program adds four numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int n3 = readInt("Enter n3: "); int n4 = readInt("Enter n4: "); int total = n1 + n2 + n3 + n4; println("The total is " + total + "."); } 15

Repeat-N-Times Idiom for (int i = 0; i < repetitions ; i++) { statements to be repeated } 16

AddNIntegers public class AddNIntegers extends ConsoleProgram { public void run() { println("This program adds " + N + " numbers."); int total = 0; for (int i = 0; i < N; i++) { int value = readInt(" ? "); total += value; } println("The total is " + total + "."); } private static final int N = 100; } 17

Repeat-Until-Sentinel Idiom while (true) { prompt user and read in a value if (value == sentinel ) break; rest of loop body } 18

AddIntegerList public class AddIntegerList extends ConsoleProgram { public void run() { println("This program adds a list of integers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; } println("The total is " + total + "."); } private static final int SENTINEL = 0; } 19

AddIntegerList public void run() { println("This program adds a list of integers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; } println("The total is " + total + "."); } AddIntegerList valuetotal This program adds a list of integers. The total is 6. ? 1 to signal the end of the list. ? 2 ? 3 ? 0 Enter values, one per line, using public void run() { println("This program adds a list of integers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; } println("The total is " + total + "."); } valuetotal 60 skip simulation 20

Exercise: Control Patterns Using the AddIntegerList program as a model, write a new AverageList program that reads a set of integers from the user and displays their average. Because 0 values might well appear, for example, in an average of exam scores, change the sentinel value so that the input stops when the user enters - 1. It is important to keep in mind that the average of a set of integers is not necessarily an integer. The AverageList program will require the following changes: –Convert the variable total to a double before computing the average –Change the definition of the SENTINEL constant –Keep a count of the number of input values along with the sum –Update the user messages and program documentation

The AverageList Program public class AverageList extends ConsoleProgram { public void run() { println("This program averages a list of numbers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; int count = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; count++; } double average = (double) total / count; println("The average is " + average + "."); } private static final int SENTINEL = -1; }

while, do while Statements while ( condition ) { statements to be repeated } do { statements to be repeated } while ( condition ) 23

DigitSum public void run() { println("This program sums the digits in an integer."); int n = readInt("Enter a positive integer: "); int dsum = 0; while ( n > 0 ) { dsum += n % 10; n /= 10; } println("The sum of the digits is " + dsum); } ndsum This program sums the digits in an integer. The sum of the digits is Enter a positive integer: 190 public void run() { println("This program sums the digits in an integer."); int n = readInt("Enter a positive integer: "); int dsum = 0; while ( n > 0 ) { dsum += n % 10; n /= 10; } println("The sum of the digits is " + dsum); } ndsum 190 public void run() { println("This program sums the digits in an integer."); int n = readInt("Enter a positive integer: "); int dsum = 0; while ( n > 0 ) { dsum += n % 10; n /= 10; } println("The sum of the digits is " + dsum); } skip simulation

Loop-and-a-Half Pattern while (true) { computation necessary to make the test if ( test for completion ) break; computation for the rest of the loop cycle } 25

Repeat-Until-Sentinel Revisited while (true) { computation necessary to make the test if ( test for completion ) break; computation for the rest of the loop cycle } while (true) { prompt user and read in a value if (value == sentinel ) break; rest of loop body } 26

for Statement for ( init ; test ; step ) { statements to be repeated } Java evaluates a for statement by executing the following steps: Evaluate init, which typically declares a control variable.1. Evaluate test and exit from the loop if the value is false.2. Execute the statements in the body of the loop.3. Evaluate step, which usually updates the control variable.4. Return to step 2 to begin the next loop cycle.5. for ( init ; test ; step ) { statements to be repeated }

for for ( init ; test ; step ) { statements to be repeated } init ; while ( test ) { statements to be repeated step ; } 28

Exercise for (int i = 1; i <= 10; i++) for (int i = 0; i < N; i++) for (int n = 99; n >= 1; n -= 2) for (int x = 1; x <= 1024; x *= 2) 29

Countdown public void run() { for ( int t = 10 ; t >= 0 ; t-- ) { println(t); } println("Liftoff!"); } t Liftoff! –1–1 public void run() { for ( int t = 10 ; t >= 0 ; t-- ) { println(t); } println("Liftoff!"); } skip simulation public void run() { for ( int t = 10 ; t >= 0 ; t-- ) { println(t); } println("Liftoff!"); } t –1–1 30

Nested for for (int i = 0; i < N_ROWS; i++) { for (int j = 0; j < N_COLUMNS; j++) { Display the square at row i and column j. } 32

Checkerboard public void run() { double sqSize = (double) getHeight() / N_ROWS; for (int i = 0; i < N_ROWS; i++) { for (int j = 0; j < N_COLUMNS; j++) { double x = j * sqSize; double y = i * sqSize; GRect sq = new GRect(x, y, sqSize, sqSize); sq.setFilled((i + j) % 2 != 0); add(sq); } sqyxjisqSize Execute the inner loop seven times to complete the checkerboard. Execute these statements six more times to complete the row. public void run() { double sqSize = (double) getHeight() / N_ROWS; for (int i = 0; i < N_ROWS; i++) { for (int j = 0; j < N_COLUMNS; j++) { double x = j * sqSize; double y = i * sqSize; GRect sq = new GRect(x, y, sqSize, sqSize); sq.setFilled((i + j) % 2 != 0); add(sq); } sqyxjisqSize skip simulation 33

Exercise: Triangle Number Table 1 = 11 = = = = = = = = = = = = 55 34

Design Issues: Triangle Number Table The program involves two nested loops. The outer loop runs through each of the values of N from 1 to the maximum; the inner loop prints a series of values on each output line. As you think about the design of the TriangleTable program, it will help to keep the following thoughts in mind: The individual elements of each output line are easier to display if you call print instead of println. The print method is similar to println but doesn’t return the cursor position to the beginning of the next line in the way that println does. Using print therefore makes it possible to string several output values together on the same line. The n th output line contains n values before the equal sign but only n – 1 plus signs. Your program therefore cannot print a plus sign on each cycle of the inner loop but must instead skip one cycle.

TriangleTable public class TriangleTable extends ConsoleProgram { public void run() { for (int n = 1; n <= MAX_VALUE; n++) { int total = 0; for (int i = 1; i <= n; i++) { if (i > 1) print(" + "); print(i); total += i; } println(" = " + total); } /* Private constants */ private static final int MAX_VALUE = 10; } 36

Simple Graphical Animation for (int i = 0; i < N_STEPS; i++) { update the graphical objects by a small amount pause(PAUSE_TIME); } 37

AnimatedSquare public void run() { GRect square = new GRect(0, 0, SQUARE_SIZE, SQUARE_SIZE); square.setFilled(true); square.setFillColor(Color.RED); add(square); double dx = (getWidth() - SQUARE_SIZE) / N_STEPS; double dy = (getHeight() - SQUARE_SIZE) / N_STEPS; for (int i = 0; i < N_STEPS; i++) { square.move(dx, dy); pause(PAUSE_TIME); } squaredydx AnimatedSquare skip simulation i public void run() { GRect square = new GRect(0, 0, SQUARE_SIZE, SQUARE_SIZE); square.setFilled(true); square.setFillColor(Color.RED); add(square); double dx = (getWidth() - SQUARE_SIZE) / N_STEPS; double dy = (getHeight() - SQUARE_SIZE) / N_STEPS; for (int i = 0; i < N_STEPS; i++) { square.move(dx, dy); pause(PAUSE_TIME); } squaredydx i

Summary Compound statements (blocks) provide structure and scoping Java control statements include if/else, switch, while, for Common Idioms are Repeat N-Times, Repeat-Until-Sentinel, and Loop-and-a-Half 39