Over and Over Again GEEN163

Similar documents
Loops. GEEN163 Introduction to Computer Programming

Bjarne Stroustrup. creator of C++

Using Classes. GEEN163 Introduction to Computer Programming

What two elements are usually present for calculating a total of a series of numbers?

Problem Solving With Loops

Using Classes. GEEN163 Introduction to Computer Programming

St. Edmund Preparatory High School Brooklyn, NY

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

Oct Decision Structures cont d

Chapter 1 Lab Algorithms, Errors, and Testing

Repetition, Looping. While Loop

Loops. CSE 114, Computer Science 1 Stony Brook University

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

ITERATION WEEK 4: EXMAPLES IN CLASS

Last Class. While loops Infinite loops Loop counters Iterations

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

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

CSIS 10A Assignment 3 Due: 2/21 at midnight

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

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

Chapter 6. Repetition. Asserting Java. Rick Mercer

Loops and Expression Types

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Repetition. Chapter 6

Repetition. Chapter 6

1 Short Answer (10 Points Each)

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

Introduction to Computer Programming

Iteration statements - Loops

Ch. 6. User-Defined Methods

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

Top-Down Program Development

More Methods GEEN163

5) (4 points) What is the value of the boolean variable equals after the following statement?

Java Coding 3. Over & over again!

Chapter 5 Lab Methods

COMP 202 Java in one week

Programming with Java

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

Arrays. Eng. Mohammed Abdualal

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

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

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

CSE 1223: Introduction to Computer Programming in Java Chapter 1 Computer Basics

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Console Input and Output

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Conditional Execution

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

COMP 202. Java in one week

The action of the program depends on the input We can create this program using an if statement

Introduction to Java Unit 1. Using BlueJ to Write Programs

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method.

COMP-202 Unit 4: Programming with Iterations

! 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

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

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

Building Java Programs

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

FOR INTERNAL SCRUTINY (date of this version: 17/2/2016) UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS

AP Computer Science Unit 1. Programs

2.8. Decision Making: Equality and Relational Operators

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

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

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Full file at

CSE 114 Computer Science I

Evaluating the Style of your programs

Task #1 The if Statement, Comparing Strings, and Flags

Selection Statements and operators

Decisions in Java IF Statements

CONDITIONAL EXECUTION

Warm-Up: COMP Programming with Iterations 1

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

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

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

CS110 Programming Language I. Lab 6: Multiple branching Mechanisms

Chapter 4: Conditionals and Recursion

Lesson 7 Part 2 Flags

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Section 2.2 Your First Program in Java: Printing a Line of Text

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Loops. Repeat after me

Program Control Flow

Program Control Flow

Chapter 8 Multi-Dimensional Arrays

Chapter 5 Lab Methods

A+ Computer Science -

Final Examination Semester 2 / Year 2011

CSCI 1226 A Test #1. Wednesday, 10 October, 2018 Name: Student #: General Instructions Read and follow all directions carefully.

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

Chapter 6. Repetition. Asserting Java. Rick Mercer

CEN 414 Java Programming

Full file at

Introduction. Data in a table or a matrix can be represented using a two-dimensional array. For example:

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Robots. Byron Weber Becker. chapter 6

Transcription:

Over and Over Again GEEN163

There is no harm in repeating a good thing. Plato

Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the three.java files to Blackboard by midnight on Friday, October 11, 2013

Summations in Mathematics In mathematics you can specify a sum as sum = which is equivalent to n i=1 1 2i sum = 1 2 + 1 4 + 1 8 + + 1 2n

Summations in Java We can write the same sum in Java double sum = 0.0; int i = 1, n = something; while (i <= n) { sum += 1.0 / (2.0 * i); i++; } sum = n i=1 1 2i

Looping Structures Java provides three different ways to create a loop while loops do while loops for loops All of them cause the program to repeat a set of statements

do while loops The do while loops is very similar to the while loop except that the loop condition is checked at the end of the loop do { sum += 1.0 / (2.0 * i); i++; } while ( i <= n );

do while Syntax When a do while loop gets to the end, it checks the logical expression. If true, it repeats the loop do { // loop body } while (logical expression);

Always Once A do while loop is always executed at least once int hen = 5; while ( hen < 4 ) { hen = hen * hen; // never executed } do { hen = hen * hen; // executed once } while( hen < 4 );

Not Repeat Until When the logical expression of a do while loop is true, the loop repeats Write the logical expression to express when the loop repeats Some students incorrectly think a do while is a repeat until where the logical expression tells you when to stop

Invert Repeat Logic In the loop body compute a new term Repeat until the term is less than 0.001 do { term = term * x / i; sum += term; i++; } while (term >= 0.001);

Watch the semicolon The following loop is wrong: int i=0; while (i < 10); { } System.out.println("i is " + i); i++; With the do loop, the semicolon is required: int i=0; do { System.out.println("i is " + i); i++; } while (i<10); 12 Logic Error Correct

What is displayed? int dog = 3, cat = 5; while ( cat < dog ) { System.out.print( dog ); dog++; } A. 3 B. 3 4 C. 3 4 5 D. nothing

Now what is displayed? int dog = 3, cat = 5; do { System.out.print( dog ); dog++; while ( cat < dog ); } A. 3 B. 3 4 C. 3 4 5 D. nothing

Thinking about programs If a program has to do something many times, it will need a loop How many times will the program loop? The parts of the program that are not repeated will be outside the loop If a program does something different some of the time, the program will have an if statement

Inputs and Outputs What is the program expected to display? What data will the program need to get to produce the results? What data types will hold the information

What is displayed? int tortoise = 3, hare = 0; do { hare += tortoise; tortoise--; } while (tortoise > 0); System.out.println(tortoise+" "+hare); 1. 3 0 2. 1 5 3. 0 6 4. none of the above

Variables Needed When you write a program, consider the variables necessary You will probably need a variable to hold each input You will probably need a variable to hold the result of a calculation

Patterns We have learned a few programming patterns that perform common tasks read until a value repeat a fixed number of times These patterns are not just one Java statement, but are several Java statements These patterns appear in many programs

Priming Read System.out.print( enter number > ); cat = keyboard.nextint(); while (cat!= endvalue ) { // do something with cat System.out.print( enter number > ); cat = keyboard.nextint(); } Same

Repeat a Fixed Number of Times Starting with one int counter = 1; while (counter <= maxvalue) { // do something counter++; }

Repeat a Fixed Number of Times Starting with zero int counter = 0; while (counter < maxvalue) { // do something counter++; }

Sample Program Consider a program that calculates the cost of purchasing some coffee. Input the number of pounds of coffee purchased and the price per pound of the coffee. Display the total cost which includes 7% sales tax. Repeat until the amount of coffee is zero or negative.

What are the inputs to the program? A. pounds of coffee B. pounds & price C. pounds, price & cost D. pounds, price, cost & tax

What results should be displayed? A. total cost B. total cost and tax C. pounds, price, tax & cost D. None of the above

Likely Variables Required Input values pounds of coffee price of coffee Output value total cost

Program Outline import java.util.scanner; public class CoffeeCost { public static void main( String[] args) { Scanner keyboard = new Scanner(System.in); // repeat // read input // calculate cost with tax // display results } }

Declare the variables import java.util.scanner; public class CoffeeCost { public static void main( String[] args) { Scanner keyboard = new Scanner(System.in); double pounds, price, cost; // repeat // read input // calculate cost with tax // display results } }

Write the input section Input the number of pounds of coffee purchased and the price per pound of the coffee

Possible Solution System.out.println( Enter the pounds of coffee ); pounds = keyboard.nextdouble(); System.out.println( Enter the price per pound ); price = keyboard.nextdouble();

Write the cost calculation and display the result Display the total cost including 7% sales tax.

Possible Solution cost = pounds * price * 1.07; System.out.println("The coffee costs "+ cost );

Adding the Loop The program is to repeat until the user enters zero or negative pounds There is no use asking the price if the pounds are zero or negative A priming read will help

Possible Solution pounds = keyboard.nextdouble(); while (pounds > 0.0) { } System.out.println( Enter the price per pound ); price = keyboard.nextdouble(); // rest of the program pounds = keyboard.nextdouble();

Complete Program public class CoffeeCost { public static void main( String[] args) { java.util.scanner keyboard = new java.util.scanner(system.in); double pounds, price, cost; } // read input System.out.println("Enter the pounds of coffee"); pounds = keyboard.nextdouble(); while (pounds > 0.0) { System.out.println("Enter the price per pound"); price = keyboard.nextdouble(); // calculate cost with tax cost = pounds * price * 1.07; // display results System.out.println("The coffee costs "+ cost ); System.out.println("Enter the pounds of coffee"); pounds = keyboard.nextdouble(); }

Software Engineering Steps Requirements Define exactly what the program is supposed to do from the user s point of view Design How will the program run Implementation Write the Java Verification Test the program looking for any errors Maintenance Fix the errors you missed the first time

Waterfall Model The waterfall model is one software engineering technique for creating programs There are several other software engineering processes

Homework Write three simple programs using while loops and if statements Flowcharts are provided to explain how to write the program Due midnight on Friday, October 11