Intro to Programming & Algorithm Design

Slides:



Advertisements
Similar presentations
Programming Logic and Design Eighth Edition
Advertisements

Solving Problems with Repetition. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly.
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Programming Logic and Design, Third Edition Comprehensive
1 Intro to Programming & Algorithm Design Functions Copyright 2003 by Janson Industries This presentation can be viewed on line in a file named: ch06.IntrotoProg.Functions.ppt.
Objectives In this chapter, you will learn about:
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Repeating Actions While and For Loops
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Computer Science 1620 Programming & Problem Solving.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Java Programming: From the Ground Up
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
Programming Logic and Design Fifth Edition, Comprehensive
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
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,
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 5: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Chapter 7 Problem Solving with Loops
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Solving Problems with Repetition Version 1.0. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C#
General Condition Loop A general condition loop just loops while some condition remains true. Note that the body of the loop should (eventually) change.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II
Loop Structures.
CHAPTER 5A Loop Structure
Repetition-Counter control Loop
( Iteration / Repetition / Looping )
Java Programming Loops
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Java Programming Loops
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Intro to Programming & Algorithm Design 4/23/2017 Intro to Programming & Algorithm Design Loops NG Assg Labs This presentation can be viewed on line in a file named: ch05.IntrotoProg.ppt Copyright 2003 by Janson Industries

4/23/2017 Objectives Explain Advantages of loops Different types of loops Common loop mistakes Show how to implement the various loop types in Java

4/23/2017 Why Loops? If a set of instructions needs to be repeated many times, best to use a loop rather than repeating the instructions Less coding Fewer mistakes For example, to keep executing with an unknown number of data records, you can't do it without a loop

Why Loops? Example Here's pseudocode for a program to double a number 4/23/2017 Here's pseudocode for a program to double a number To double another number we have to rerun the program For example... Module main Declare Integer numToDouble, result Display “Enter number to double and press Enter” Input numToDouble result = numToDouble * 2 Display “2 X ”, numToDouble, “ = ”, result End Module

To double another number, have to issue the java command again We want program to just ask for another number...

4/23/2017 Why Loops? Example With a loop, we could have the instructions run again And again, and again, and.... Module main Declare Integer numToDouble, result BeginLoop Display “Enter number to double and press Enter” Input numToDouble result = numToDouble * 2 Display “2 X ”, numToDouble, “ = ”, result EndLoop End Module

4/23/2017 Why Loops? This is why loops have to check a control variable to see if they should process the statements again How and when the check is done is the difference between the different types of loops Condition-controlled Count-controlled

4/23/2017 Why Loops? Condition-controlled loops use a true/false condition to determine how many times to loop While executes when condition true Do While executes when condition true Do Until executes when condition false Count-controlled loops execute a specific number of times For

4/23/2017 Why Loops? Condition-controlled loops also differentiated by when the condition is checked While is a pre-test loop Do While is a post-test loop Do Until is a post-test loop

Loops While loop – pre-test Checks the condition first and only executes if condition true : : : While hair = “dirty” Lather Rinse Display "Is hair dirty or clean" Input hair End While

Loops 4/23/2017 While Condition check done first If check true, executes statements Lather and rinse will not be executed if condition is false Input… Display… Is hair = “dirty” True Lather Rinse False False

4/23/2017 Loops In While, Do While, and Do Until loops, the programmer explicitly manipulates the control variable(s) In java, while loop syntax is Keyword while Condition (in parenthesis) Statements to execute (in braces) while (condition) { statements to execute }

Simple pre-test loop example Notice loop runs 4 times even though check is "counter < 4" Control variable (counter) defined outside of loop and manipulated inside loop

Loops Do While – post-test Do Until – post-test Checks condition at end and executes if condition true Do Until – post-test Checks condition at end and executes if condition false Loops Do : : While hair = “dirty” Do : : Until hair = “clean”

4/23/2017 Loops Do While condition test done at end of loop Lather and rinse will always be executed at least once whether the condition is true or not but only continues if true Lather Rinse Is hair = “dirty” True False

4/23/2017 Loops Do Until Condition test done at end of loop Lather and rinse will always be executed at least once whether the condition is true or not but only continues if false Lather Rinse Is hair = “clean” False True

Do While Loops In java, do while loop syntax is Keyword do 4/23/2017 Do While Loops In java, do while loop syntax is Keyword do Statements to execute (in braces) Keyword while Condition (in parenthesis) do { statements to execute } while(condition)

Answer: if numberOfTimesToLoop = 0 Simple post-test loop example - Notice loop runs 4 times (just like pretest) What condition(s) would result in different output for the different loop types? Answer: if numberOfTimesToLoop = 0

Do Until Loops In java, there is no Do Until 4/23/2017 Do Until Loops In java, there is no Do Until Closest you can come to a Do Until is use a Do While and negate the condition do { statements to execute } while(!condition)

For Loop A little complicated 4/23/2017 For Loop A little complicated Does a lot of stuff very compactly Most for statements allow the programmer to specify A loop control variable An initial value for the variable An evaluation condition A Boolean expression with the loop control variable A variable update value

For Loop Pseudo code example: ctr = 1 to 3 step 1 Declare Integer ctr 4/23/2017 Pseudo code example: Declare Integer ctr For ctr = 1 to 3 step 1 statements to be repeated End For Defines the loop control variable ctr ctr = 1 to 3 Initializes ctr to 1 and defines the max value for ctr step 1 defines the increment value as 1

For Loop If you don’t specify a step value the default is 1 4/23/2017 For Loop If you don’t specify a step value the default is 1 Declare Integer ctr For ctr = 1 to 2 Lather Rinse End For

For Loop Executes a defined number of times In this case twice 4/23/2017 For Loop Executes a defined number of times In this case twice Also called a definite loop, counted loop, counter controlled loop for ctr =1 to 2 True Lather Rinse False False

Java For Loop The for keyword Then in parenthesis 4/23/2017 The for keyword Then in parenthesis Loop control variable definition (optional) and initialization Semicolon The loop condition evaluation The step increment definition Then in braces the statements to be repeated for (int ctr = 1; ctr < 3; ctr = ctr + 1) { statements to be repeated }

Java For Loop Example int ctr = 1 ctr < 3 ctr = ctr + 1 4/23/2017 Example for (int ctr = 1; ctr < 3; ctr = ctr + 1) { statements to be repeated } int ctr = 1 Creates the variable ctr Initializes ctr to 1 ctr < 3 Defines the condition to check ctr = ctr + 1 Defines the increment as 1

For Loop If the loop is going to execute a fixed number of times 4/23/2017 For Loop If the loop is going to execute a fixed number of times For loop easier than while or do while Instead of statements to Define the control variable Define the limit Increment the control variable And the do or do while keywords You use the for statement to do all those things

Notice how much less code is needed

For Loop To truly understand the For loop, you have to understand 4/23/2017 For Loop To truly understand the For loop, you have to understand The generally accepted interpretation of the pseudocode and/or flowchart text When all the "pieces" of the for statement are performed

4/23/2017 For Loop If the pseudocode had specified 0 to 99 (0 and 99 are inclusive) It means the statements should be executed 100 times Once when it was 0 Once when it was 1 Etc, etc, etc Once when it was 99

4/23/2017 For Loop To get the for loop to work the same way with java, could specify any of these int ctr = 0; ctr <100; ctr = ctr + 1 int ctr = 0; ctr <= 99; ctr = ctr + 1 int ctr = 1; ctr <101; ctr = ctr + 1 int ctr = 1; ctr <= 100; ctr = ctr + 1

For Loop Why? Because the for does "int ctr = 1" first and only once 4/23/2017 For Loop Why? Because the for does "int ctr = 1" first and only once Then repeatedly The condition is checked If condition is true Statements are executed Ctr is incremented by one When the condition is false The statement after the End For is executed

For Loop int ctr = 1 Is ctr < 3 Perform Statements ctr = ctr +1 4/23/2017 For Loop int ctr = 1 Is ctr < 3 Perform Statements ctr = ctr +1 True False

For Loop In the pseudocode 1 to 2 means 4/23/2017 In the pseudocode 1 to 2 means Do the statements while the control variable is equal to 1 or 2 This means The variable is initially set to 1 Condition is checked The statements are performed The variable is incremented to 2 The variable is incremented to 3 The statement after the End For is performed

Sentinel Values 4/23/2017 Sometimes you want a loop to execute until a user enters a value the means “stop the loop” Called a sentinel value While or Do While best for this Declare Integer userInput, result Input userInput While (userInput > 0) result = userInput * 2 Display result End While

Back To Our Original Problem 4/23/2017 Back To Our Original Problem Want to run doubling app until user indicates to stop In addition, we want to add non-logical (aka physical) requirements to design User interface Formatting

Back To Our Original Problem 4/23/2017 Back To Our Original Problem External Design (XD) Enter number you would like to double and press Enter. 4 2 x 4 = 8 -1 OK, you entered a value <= 0, ending execution

Final flow chart and pseudocode

4/23/2017 Notice design does not worry about peculiarities of the programming language

Create a Raptor FC and run to verify we have the correct logic 4/23/2017 Create a Raptor FC and run to verify we have the correct logic

Final java class looks like this import java.io.IOException; import java.util.Scanner; public class DoubleWithWhile { public static void main(String[] args) { // Variable and object needed to read from command line Scanner keyboard = new Scanner(System.in); // Variables needed to hold input, intermediate values, and results int numToDouble = 0; int result = 0; // Prints out a blank line and instruction System.out.println(" "); System.out.print("Enter number would you like to double and press Enter. "); // Priming read numToDouble = keyboard.nextInt(); // Start of loop and check for sentinel value while (numToDouble > 0){ // Calculates and displays result result = numToDouble * 2; System.out.println("2 X " + numToDouble + " = " + result); 4/23/2017 Final java class looks like this

// Prints out a blank line and instruction System.out.println(" "); 4/23/2017 // Prints out a blank line and instruction System.out.println(" "); System.out.print("Enter number would you like to double and press Enter. "); // Reads next user input numToDouble = keyboard.nextInt(); // End of loop } // Quitting message System.out.print("OK, you entered a value <= 0, ending execution. "); // End of method // End of class

With a loop, problem solved

Loops Lots of reasons to use loops Accumulating Data validation 4/23/2017 Lots of reasons to use loops Accumulating A shopping cart of items Totals Data validation Declare Integer empAge Display "Enter employee age" Input empAge While (empAge > 95 OR empAge < 16) Display "Enter a valid age between 16 & 95" End While

Totaling in a Loop Module main Declare Real cost, totalCost 4/23/2017 Module main Declare Real cost, totalCost Display “Enter first item cost" Input cost While (cost > 0) totalCost = totalCost +cost Display “Enter next item cost or zero to end" End While Display “The total cost for all items is $“ , totalCost End Module

Can keep count of how many items are entered and display 4/23/2017 Module main Declare Real cost, totalCost Declare Integer counter = 0 Display “Enter first item cost" Input cost While (cost > 0) counter = counter + 1 totalCost = totalCost +cost Display “Enter next item cost or zero to end" End While Display “The total cost for the “ , counter , “ item(s) is $“ , totalCost End Module Can keep count of how many items are entered and display

Nested Loops Loops within loops 4/23/2017 Nested Loops Loops within loops Example, a report that reads and prints a file's contents and has the following format: Report header For each page A page header with page number For next 33 items Print line item A page footer with page number Report footer

Exercise XD Report will look like Report Header Page Header on Page # 4/23/2017 Report Header Exercise XD Report will look like Page Header on Page # ################################################## Page Footer on Page #

Exercise XD Can be a variable number of pages Report Footer 4/23/2017 Page Header on Page # ################################################## Page Footer on Page # Exercise XD Can be a variable number of pages Report Footer

4/23/2017 Nested Loops When a file is read, system returns a boolean value to indicate if there is anymore data Called an "end of file" indicator Indicator abbreviated as eof eof has a boolean value of true or false Can be used to control looping

Nested Loops Inner Loop Outer Loop Module main 4/23/2017 Nested Loops Module main Declare Integer pageCtr = 1, lineCtr = 0 Print Report Header and Skip to next page pageCtr = pageCtr + 1 Read record From file While (not eof) Print Page Header and pageCtr While (lineCtr < 33 AND not eof) Print item From record lineCtr = lineCtr + 1 End While lineCtr = 0 Print Page Footer and pageCtr Skip to next page Print Report Footer End Module Inner Loop Outer Loop

Exercise Design (SFC) an application that: 4/23/2017 Design (SFC) an application that: Gets customer account data from a file that has account number, customer name, and balance due For each customer: Print the account number and name Then for each month for the next 10 months Print the customer’s projected balance Assume: No finance or interest charge Customer makes no new purchases Customer pays off the balance with equal monthly payments of 10 percent of the original balance due

Algorithm 1. Read first record from the file 2. While not eof 4/23/2017 Algorithm 1. Read first record from the file 2. While not eof a. Display account number, customer name b. Then 10 times i. Subtract 10% from balance due ii. Display balance due c. Read next record from the file

Exercise XD Output will look like… Account Number: ####### 4/23/2017 Output will look like… Account Number: ####### Customer: Xxxxx Xxxxxx Balance over next 10 months ######## Account Number: ########

Exercise What's input and what variables will you need to hold them? 4/23/2017 Exercise What's input and what variables will you need to hold them? acctNum for Account number custName for Customer name balanceDue for Balance due Based on calculation what variables will you need to hold intermediary and results? paymentAmt for 10 percent of the balance

Exercise So in flow chart, what's first? Then what? Variable definition Then what? Priming read 4/23/2017

Exercise 4/23/2017 Then what? While that checks not eof

Exercise 4/23/2017 Then what? Print headers

Exercise 4/23/2017 Then what? Calc paymentAmt

Exercise Then what? For loop that runs 10 times to print balances 4/23/2017 Then what? For loop that runs 10 times to print balances For loop is nested within the while loop

Exercise 4/23/2017 Then what? Calc balanceDue and print it out

Exercise What happens when last balance printed? Blank line 4/23/2017 Exercise What happens when last balance printed? Blank line Read next record Check for end of file

Having an incorrect comparison 4/23/2017 Loop Gotchas Having an incorrect comparison

4/23/2017 Loop Gotchas Not initializing the control variable – in java, should always initialize

Not changing the control variable 4/23/2017 Loop Gotchas Not changing the control variable

Loop Gotchas The last example resulted in an infinite loop 4/23/2017 Loop Gotchas The last example resulted in an infinite loop The condition is never false Loop statements continually executed Can also happen because of a bad/trivial condition (always true) 1 == 1 End program execution by pressing and holding Ctrl key and then pressing C key (Crtl + C)

4/23/2017 Loop Exercise Assg 1 Program will calculate the number of bills needed for a dollar amount (until 0 entered) For instance, Program prompts user What is the dollar amount? User enters 58 Program displays 2 twenty(ies), 1 ten(s), 1 five(s) and 3 one(s) 20 is the largest denomination, no 2 dollar bills.

Loop Exercise Attack this in two parts Design everything else first 4/23/2017 Loop Exercise Attack this in two parts How to calculate the bills Everything else Design everything else first Answer 1

Bills Exercise Continued 4/23/2017 Bills Exercise Continued How to figure out the number of bills a little trickier First: you need variables to keep track of the number of bills for each denomination (bill counters) Couple of ways to do calc if value > than largest denomination Add one to that bill counter Subtract denomination from amount and check again else if value > second largest

Bills Exercise Continued 4/23/2017 Bills Exercise Continued So for example, if 58 (dollars) entered Check if dollars is bigger than 20 Yes Add one to 20 counter Subtract 20 from dollars, check again No if value > than 2nd largest denomination Add one to that bill counter Subtract denomination from dollars and check again else if …. Answer 2

Bills Exercise Continued 4/23/2017 Bills Exercise Continued Alternatively Divide the amount by the biggest denomination twentiesCtr = dollars/20 This assumes dolls is an integer so that the decimal remainder will be truncated Calc the remainder dollars = dollars – (twentiesCtr * 20) Divide the amount by the 2nd biggest denomination etc. Alt Answer

Bills Exercise Continued 4/23/2017 Bills Exercise Continued Let’s prove that it works by creating a Raptor FC Answer 3

4/23/2017 Non-graded Assg 1 Using nested loops, write a program to display the outer loops counter value as follows Don’t use math to generate numbers like 4,444 or 55,555 Send file, email topic Ch05Assg1 Need a hint? 1 22 333 4444 55555

Points to Remember Loops are control structures that repeat actions 4/23/2017 Loops are control structures that repeat actions Makes computer programs more efficient Four general types While DoWhile DoUntil For Loops characterized as pretest or posttest

Points to Remember All require Can be nested Beware the infinite loop 4/23/2017 Points to Remember All require A loop control variable Which must be initialized and updated A condition that tests the control variable against a sentinel value Can be nested Beware the infinite loop

Assignments Non-Graded Graded Ch05Assg1 Chap 5 labs 4.1-4.4 4/23/2017 Assignments Non-Graded Ch05Assg1 Chap 5 labs 4.1-4.4 Graded Chap 5 lab 4.5