Top-Down Program Development

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

Last Class. While loops Infinite loops Loop counters Iterations

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

Computer Science is...

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition, Looping. While Loop

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

Selection and Repetition Revisited

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

Java I/O and Control Structures

COMP-202 Unit 4: Programming with Iterations

Loops / Repetition Statements

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

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

STUDENT LESSON A12 Iterations

Example: Monte Carlo Simulation 1

1 Short Answer (10 Points Each)

Java Coding 3. Over & over again!

Java I/O and Control Structures Algorithms in everyday life

CSC 1051 Data Structures and Algorithms I

Repetition. Chapter 6

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

Repetition. Chapter 6

Chapter 4: Control structures. Repetition

Selection and Repetition

Recap: Assignment as an Operator CS 112 Introduction to Programming

CSC 1051 Data Structures and Algorithms I

Chapter 4: Control structures

Problem Solving With Loops

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

Introduction to the Java Basics: Control Flow Statements

COMP 202 Java in one week

CS 112 Introduction to Programming

Selection and Repetition Revisited

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

INFO Object-Oriented Programming

Warmup : Name that tune!

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

Iteration statements - Loops

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Ch. 6. User-Defined Methods

Midterm Examination (MTA)

Bjarne Stroustrup. creator of C++

CSE 114 Computer Science I

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.

Over and Over Again GEEN163

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Flow of Control: Loops. Chapter 4

COMP 202. Java in one week

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

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

Chapter 17. Iteration The while Statement

Warm-Up: COMP Programming with Iterations 1

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

Selection and Repetition

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

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

Introduction to Java & Fundamental Data Types

REPETITION CONTROL STRUCTURE LOGO

CompSci 125 Lecture 11

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

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

CSC 1051 Data Structures and Algorithms I

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Dept. of CSE, IIT KGP

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

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

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

Controls Structure for Repetition

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Chapter Goals. Contents LOOPS

Course Outline. Introduction to java

CMPT 125: Lecture 4 Conditionals and Loops

Lecture 14. 'for' loops and Arrays

! 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

CS111: PROGRAMMING LANGUAGE II

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

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

Assignment 2.4: Loops

Decision-Making and Repetition

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Repetition Structures

Chapter 4 Introduction to Control Statements

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

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Repetition, Looping CS101

Elementary Programming

CIS 110: Introduction to Computer Programming

Building Java Programs

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

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

Fundamentals of Programming Session 13

Oct Decision Structures cont d

Transcription:

Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable pieces Each of these pieces can then be broken down again into smaller pieces You then solve each of these pieces, and combine the solutions to these pieces to form the solution to the original problem

Top-Down Development: Steps Applying top-down development consists of doing the following: 1.First, read and understand the problem 2.Then, subdivide the problem into pieces. Each chunk is one task, like initializing variables, getting inputs, generating outputs, if-statements and loops 3.Then sort all these elements in the correct order. 4.Last, only now start writing your code Steps 1-3 are either done in your head or on scrap paper. They are not done using the language editor or compiler. They do not even need to be in Java, they could be in simple English / French / your first language /...

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

Repetition Statements Repetition statements allow us to execute a (set of) statement(s) multiple times, repetitively; these statements are often called loops

Repetition Statements in Java Java has two main kinds of repetition statements: the while loop and the for loop While and for loops are equivalent However, in certain circumstances, choosing one of these statements over the other results in a program that is easier to understand.

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++;

to increment or decrement the value stored in x Recall: increment/decrement operators Remember that if you have an int variable, you can do x++ ++x x-- --x

Recall: increment/decrement operators for(int x = 0; x < 4; x++) { System.out.println( I have to + write this over and over );

Recall: if statement i f ( condition) One statement i f ( condition) One block of statements Example: if(x!= 0) width = x + 5; Example: if(x == 0){ z = x + 3; x = 5;

while loops are similar in structure to if statements whi l e ( condition) One statement whi l e ( condition) One block of statements The difference is that when we reach the end of the one statement or block, we go back to the start of the while loop and re-test the condition

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++;

x = 0; if (x < 4) { System.out.println(...); x++; if (x < 4) { System.out.println(...); x++; if (x < 4) { System.out...

What does this display? public class Counter { public static void main(string[] args) { final int LIMIT = 3; int count = 1; while (count <= LIMIT) count = count + 1; System.out.println(count); System.out.println("Done.");

What does this display? public class Counter { public static void main(string[] args) { final int LIMIT = 3; int count = 1; while (count <= LIMIT){ System.out.println(count); count = count + 1; System.out.println("Done.");

Components of a while loop condition while (x < 4) { System.out.println( I have to write + this over and over. ); x++;

Components of a while loop while (x < 4) { System.out.println( I have to write + this over and over. ); x++; loop body

Definition: iteration An iteration is a single execution of the instructions in the loop body.

This loop consists of 4 iterations. int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; I hav e to wr i te thi s o v e r and o v e r. I hav e to wr i te thi s o v e r and o v e r. I hav e to wr i te thi s o v e r and o v e r. I hav e to wr i te thi s o v e r and o v e r.

How many iterations does the following loop consist of? int x = 4; while (x > 4) { System.out.println( I have to write + this over and over. ); x++;

How many iterations does the following loop consist of? int x = 6; while (x > 4) { System.out.println( I have to write + this over and over. ); x--;

How many iterations does the following loop consist of? int x = 6; while (x < 4) { System.out.println( I have to write + this over and over. ); x++;

Logic of a while Statement false condition true statement (rest of the program)

What is wrong here? public class Abyss { public static void main(string[] args) { int count = 1; System.out.println("I'm going in..."); while (count <= Integer.MAX_VALUE) { System.out.println(count); count = count - 1; System.out.println("Found the bottom of the abyss!");

Infinite Loops: A Common Logical Error An infinite loop executes until the user interrupts (terminates) the program. This is what happens when the statements in the body of a while loop never update the loop condition to false

What will be displayed? Why is it the wrong result? Correct the program so that it displays the right sum. publ i c c l as s Sum { publ i c s t ati c v o i d main( Str i ng [ ] ar g s ) { fi nal i nt MAX = 5; i nt s um = 0; i nt i = 1 ; whi l e ( i < MAX) { s um = s um + i ; Sys te m. o ut. pr i nt l n( Sum: + s um); i = i + 1 ; Sys te m. o ut. pr i nt l n( i : + i ) ; Sys te m. o ut. pr i nt l n( ) ; Sys te m. o ut. pr i nt l n( The s um of i nte g e r s fr o m 1 to + MAX + i s : + s um);

Sum Sum: 1 i : 2 Sum: 3 i : 3 Sum: 6 i : 4 Sum: 1 0 i : 5 The s um of the i nte g e r s fr o m 1 to 5 i s : 1 0

Off-By-One Errors It is a common logical error to write loop conditions that result in the loop body being executed one time too few, or one time too many You should always test your code to check that your loops conditions do not cause such errors

What will be displayed? Why is it the wrong result? Correct the program so that it displays the right sum. publ i c c l as s Anoth e r Sum { publ i c s t ati c v o i d main( Str i ng [ ] ar g v ) { fi nal i nt MAX = 5; i nt i = 0; i nt s um = 0; whi l e ( i <= MAX) { i = i + 1 ; Sys te m. o ut. pr i nt l n( i : + i ) ; s um = s um + i ; Sys te m. o ut. pr i nt l n( s um: + s um); Sys te m. o ut. pr i nt l n( ) ; Sys te m. o ut. pr i nt l n( The s um of i nte g e r s fr o m 1 to + MAX + i s : + s um);

i : 1 s um: 1 i : 2 s um: 3 i : 3 s um: 6 i : 4 s um: 1 0 i : 5 s um: 1 5 i : 6 s um: 21 The s um of the i nte g e r s fr o m 1 to 5 i s : 21

Nested Loops Like if and if-else statements, loops can be nested as well Every time the body of the outer loop is executed, the inner loop will go through its entire set of iterations

What does this display? publ i c c l as s Nes te dlo o p { publ i c s t ati c v o i d main( Str i ng [ ] ar g s ) { fi na l i nt MAX = 4; i nt o ute r Co unt, i nne r Co unt ; o ute r Co unt = 1 ; whi l e ( o ute r Co unt <= MAX) { i nne r Co unt = 1 ; whi l e ( i nne r Co unt <= MAX) { Sys te m. o ut. pr i nt ( ( + o ute r Co unt +, + i nne r Co unt + ) ) ; i nne r Co unt ++; Sys te m. o ut. pr i nt l n( ) ; o ute r Co unt ++; Sys te m. o ut. pr i nt l n( Done. ) ;

( 1, 1 ) ( 1, 2) ( 1, 3 ) ( 1, 4) ( 2, 1 ) ( 2, 2) ( 2, 3 ) ( 2, 4) ( 3, 1 ) ( 3, 2) ( 3, 3 ) ( 3, 4) ( 4, 1 ) ( 4, 2) ( 4, 3 ) ( 4, 4) Done.

What does this display? publ i c c l as s Anoth e r Nes te dlo o p { publ i c s t ati c v o i d main( Str i ng [ ] ar g s ) { fi na l i nt MAX = 4; i nt o ute r Co unt, i nne r Co unt ; o ute r Co unt = 1 ; whi l e ( o ute r Co unt <= MAX) { i nne r Co unt = 1 ; whi l e ( i nne r Co unt <= o ute r Co unt ) { Sys te m. o ut. pr i nt ( ( + o ute r Co unt +, + i nne r Co unt + ) ) ; i nne r Co unt ++; Sys te m. o ut. pr i nt l n( ) ; o ute r Co unt ++; Sys te m. o ut. pr i nt l n( Done. ) ;

( 1, 1 ) ( 2, 1 ) ( 2, 2) ( 3, 1 ) ( 3, 2) ( 3, 3 ) ( 4, 1 ) ( 4, 2) ( 4, 3 ) ( 4, 4) Done.

Part 2: The for Statement

Example: a for loop for(int x = 0; x < 4; x++) { System.out.println( I have to write + this over and over. ); I hav e to wr i te thi s o v e r and o v e r. I hav e to wr i te thi s o v e r and o v e r. I hav e to wr i te thi s o v e r and o v e r. I hav e to wr i te thi s o v e r and o v e r.

for loops are a little different, but still quite similar fo r ( initialization; condition; follow-up action) One statement fo r ( initialization; condition; follow-up action) One block of statements

Components of a for loop for(int x = 0; x < 4; x++) { System.out.println( I have to write + this over and over. );

Logic of a for Statement initialization false condition evaluated true statement increment (rest of the program)

Logic of a for Statement x=0 false x<5 true {loop body x++ (rest of the program)

for Loops as while Loops A for loop is equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment;

for Loops as while Loops A for loop is equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; Excellent exercise to do at home! Find a for-loop example and: Rewrite it as a while loop Rewrite it as a series of if-else statements.

Execution of a for Loop Like in a while loop, the condition of a for loop is tested prior to entering the loop body If the condition of a for loop evaluates to false initially (that is, it evaluates to false the first time it is evaluated), the statement is never executed Therefore, the body of a for loop will be executed zero or more times A for loop is well suited for executing a specific number of times that can be determined in advance

AnotherCounter.java public class AnotherCounter { public static void main(string[] args) { final int LIMIT = 3; for (int count=1; count <= LIMIT; count++) { System.out.println(count); System.out.println("Done.");

AnotherCounter.java public class AnotherCounter { public static void main(string[] args) { final int LIMIT = 3; for (int count=1; count <= LIMIT; count++) { System.out.println(count); System.out.println("Done."); LIMIT: 3 Console: 1 2 3 Done. count: 1 2 3 4 What does this display?

What shape does this display? public class Stars { public static void main (String[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) { System.out.print("*"); System.out.println();

* ** *** **** ***** ****** ******* ******** ********* **********

What Shape does this Display? public class WhatIsThis { public static void main(string[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int space = 1; space <= MAX_ROWS - row; space++) { System.out.print(" "); for (int star = 1; star <= row * 2; star++) { System.out.print("*"); System.out.println(); for (int base = 3; base > 0; base--) { for (int space = 1; space <= MAX_ROWS-1; space++) { System.out.print(" "); System.out.println("**");

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Details on the for Statement Each expression in the header of a for loop is optional If the initialization portion is left out, no initialization is performed If the condition portion is left out, it is always considered to evaluate to true, and therefore creates an infinite loop If the increment portion is left out, no increment operation is performed Both semi-colons are always required in the for loop header

for Loop: Exercise 1 Complete the main() method of the Multiples class by adding code that displays all the multiples of a number entered by the user that exist between 1 and an upper limit also entered by the user The completed program MUST display 5 multiples of the number entered by the user per line, except for the last line, which may contain less In addition, the completed program MUST display a tab character ( '\t') between every multiple displayed on a line Finally, the completed program MUST use a for loop to generate and display the multiples of the number entered by the user

Multiples.java (1 / 2) import java.util.scanner; public class Multiples { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); final int PER_LINE = 5; int value; int limit; System.out.print ("Enter a positive value: "); value = keyboard.nextint(); System.out.print ("Enter an upper limit: "); limit = keyboard.nextint(); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:"); // Continued on next slide

Multiples.java (2 / 2) // Continued from previous slide // Add your code here

for Loop: Exercise 2 Complete the main() method of the Approximation class by adding code that approximates the number e (the basis of the natural logarithm). The number e can be approximated by the following sum: e = (1 / 0!) + (1 / 1!) + (1 / 2!) + (1 / 3!) +... The main() method of the Approximation class asks the user to enter the number of terms of be computed; your task is to add code which computes each of these terms and adds them together to form the approximation of e The obvious way of solving this problem involves using nested loops, where the inner loop computes the required factorial during every iteration of the outer loop. Can you find a way to solve this problem using only one loop?

Approximation.java import java.util.scanner; public class Approximation { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int n; System.out.print("Please enter the number of terms: "); n = keyboard.nextint(); // Add your code here

Stars.java public class Stars { public static void main (String[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) { System.out.print("*"); System.out.println(); What shape does this program display?

WhatIsThis.java (1 / 2) public class WhatIsThis { public static void main(string[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int space = 1; space <= MAX_ROWS - row; space++) { System.out.print(" "); for (int star = 1; star <= row * 2; star++) { System.out.print("*"); System.out.println(); for (int base = 3; base > 0; base--) { for (int space = 1; space <= MAX_ROWS-1; space++) { System.out.print(" "); // Continued on next slide

WhatIsThis.java (2 / 2) // Continued from previous slide System.out.println("**"); What shape does this program display?

Part 4: Exercises

Exercises (1) 1.Write a program which consists of a single class called Factor that asks the user to enter a positive integer (including zero). The program then displays that number and its greatest prime factor. The program repetitively does this until the user inputs a negative number.

Exercises (2) 2.Write a program which consists of single class called Boxes that asks the user for a positive integer number n. The program then displays a solid square with side length n next to a hollow square with side length n. The program does nothing if the user inputs 0 or a negative value. If example, if the user enters 4, the following will be displayed: **** **** **** * * **** * * **** ****

Exercises (3) 3.One can approximate the square root of any number a using the following sequence: x 0 = a / 2 x i+1 = (x i + a / x i ) / 2 Write a program which consists of a single class called SquareRoot. This class defines a main() method that asks the user to enter a number a, and a number of iterations n, and reads these values from the keyboard. The program then computes the n th term in the above sequence, thus approximating the value of of the square root of a, and displays it to the screen.

Assignment Operators (1) Example 1: total += 5; is equivalent to total = total + 5; Example 2: result *= count1 + count2; is equivalent to result = result * (count1 + count2);