Announcements Lab 3 was due today Assignment 2 due next Wednesday

Slides:



Advertisements
Similar presentations
COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Advertisements

Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
COMP 110 Loops Tabitha Peck M.S. February 11, 2008 MWF 3-3:50 pm Philips
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Java Programming: From the Ground Up
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
COMP 110: Spring Announcements Lab 1 was due at noon Lab 2 on Friday (Bring Laptops) Assignment 1 is online TA Office hours online 30-min quiz at.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Programming with Loops. When to Use a Loop  Whenever you have a repeated set of actions, you should consider using a loop.  For example, if you have.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
COMP Loop Statements Yi Hong May 21, 2015.
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
CSC 211 Java I for loops and arrays.
CSC111 Quick Revision.
Lecture 7: Repeating a Known Number of Times
Chapter 5: Control Structures II
Loop Structures.
Java's for Statement.
Chapter 5: Control Structure
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Repetition-Counter control Loop
Topics Introduction to Repetition Structures
Selected Topics From Chapter 6 Iteration
LOOPS.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Control Structure Senior Lecturer
While Loops.
CSS161: Fundamentals of Computing
COMP 110 Loops, loops, loops, loops, loops, loops…
Chapter 6: Repetition Statements
Loop Strategies Repetition Playbook.
Let’s all Repeat Together
Announcements Lab 6 was due today Lab 7 assigned this Friday
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 14, 2011
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Loops.
Announcements Program 1 due noon Lab 1 due noon
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Announcements Lab 3 was due today Assignment 2 due next Wednesday Quiz at end of class

Questions? Last time we covered loops: for while do-while

Today in COMP 110 More Programming with Loops review nested loops

Review The while statement can be used to construct a loop in Java while(Boolean_Expression) { Statement_1 Statement_2 … Statement_N } As long as Boolean_Expression is true, the statements in the loop body are executed

Review Do-While Syntax Execute Statements_1…N Statement_N } while (Boolean_Expression); //note the semicolon! Execute Statements_1…N If Boolean_Expression is true, repeat

Review For Loop Syntax for(Initializing_Action; Boolean_Expression; Update_Action) { Statement_1 Statement_2 … Statement_N } Initializing_Action is used to initialize a counter variable Boolean_Expression is the stopping condition for the loop Update_Action is used to update a counter variable after the loop body is executed

Review Choosing a loop Do-While For While When you want the body to be executed at least once Useful for checking user input For More convenient/readable when the number of iterations is known beforehand, e.g. stored in some counter variable While Safest choice, can be used to create any kind of loop When it might be necessary for the loop to iterate zero times

Nested Loops It’s possible, and sometimes necessary to use loops inside other loops This is called nesting Just like with nested if-statements

Nested Loops Example int sum = 0; int i = 0; while(i < 10) { for(int j = 0; j < 20; j++) sum = sum + j; i++; }

Commas in For Statements We can perform multiple initializations or updates using the comma operator int n,c; int product; for (n = 1, c = 1; n <= 5; c = c + 2, n++) { product = product * c * n; } System.out.println(product);

Designing Loops Creating a loop involves designing three things Initialization of Variables Loop Body Stopping Condition

Designing a Loop Body How to determine what statements should be inside the body of a loop? Example Calculate the sum of numbers entered by the user

Designing a Loop Body Repeated statements become your loop body Output instructions to the user Initialize variables Prompt user for input Read a number into variable next sum = sum + next; ... Output sum Repeated statements become your loop body Statements that are only done once are not part of your loop body

Pseudocode with Loop Body Output instructions to the user Initialize variables Do the following for the appropriate number of times: { Prompt user for input Read a number into variable next sum = sum + next; } Output sum Initializing statements How do we end the loop? How many iterations?

Initializing Statements Variables used in your loop need to be initialized (set to a value) before the loop next Read a number into variable next We read a new value for next before using it during each iteration of the loop so we do not need to initialize it sum sum = sum + next; sum is on the right side of an assignment statement. sum MUST have a valid value before the loop starts.

Initialize Sum What should sum be initialized to? Consider the first iteration After executing the first iteration, the expected value of sum should be sum == next (the first input value) The assignment statement is sum = sum + next; Therefore, initial value of sum is sum = 0;

Loop with Initializations Output instructions to the user sum = 0; Do the following for the appropriate number of times: { Prompt user for input Read a number into variable next sum = sum + next; } Output sum Initializing statements

Ending Loops How to choose a stopping condition for your loop? Count-controlled loops When you know number of loop iterations for(count = 0; count < iterations; count++) User-controlled loops Ask-before-iterating Sentinel value Boolean The value of a boolean indicates whether the loop should stop

Count-Controlled Loops A program to average exam scores input by the user We know the size of the class is "numStudents" double next, average, sum=0; int i; for(i = 0; i < numStudents; i++) { //# iterations is fixed next = keyboard.nextDouble(); sum = sum+next; } average = sum/numStudents;

Ask-Before-Iterating Sometimes it is useful to have the user decide when a loop should end String answer; do { //perform some computations System.out.print("Continue? yes/no"); answer = keyboard.nextLine(); } while (answer.equalsIgnoreCase("yes")); Do this on board

Sentinel Value Signal end of input System.out.print("Enter a negative number to end the loop"); int next = keyboard.nextInt(); int sum = 0; while (next >= 0) { sum = sum + next; System.out.print("Enter a number: "); next = keyboard.nextInt(); }

Booleans int next, sum = 0; boolean moreNumbers = true; Scanner keyboard = new Scanner(System.in); while(moreNumbers ) { next = keyboard.nextInt(); if (next < 0) moreNumbers = false; //this will be the last iteration else sum = sum + next; } System.out.print("The sum is " + sum);

Off-by-One errors Loop repeats one too many or one too few times for (count = 1; count < 10; count++); Loop for count = [1,9] (9 iterations) for (count = 1; count <= 10; count++); Loop for count = [1,10] (10 iterations) for (count = 0; count <= 10; count++); Loop for count = [0,10] (11 iterations) Do this on board

Exercise What does the following display? int product = 1; int max = 4; for(int i = 0; i <= max; i++) product = product * i; System.out.println("The product is " + product); Output The product is 0

Example Problem Find the lowest and highest ages in the class

Loop Body Get age of student 1 Update min/max ages ... Get age of student 38 End loop Output min and max ages

Min/Max Ages int min = 2000; // initialize to large value int max = 0; // initialize to small value for (int count = 1; count <= 38; count++) { //Ask student #count for age ... //Compute min and max if (age > max) max = age; if (age < min) min = age; } //Output min and max ages

Min/Max Ages if (age > max) max = age; if (age < min) min = age; 2000 20 23 18 25 12 94 36 … if (age > max) max = age; if (age < min) min = age;

Debugging What to do if there’s something wrong with your program, but you’re not sure what? Trace the variables Watch the variables change as the program executes

Tracing Variables Two ways to trace variables Manually Automatically Using print statements Automatically Using the debugger

Manual Tracing Insert print statements to output the values of variables System.out.print("Enter a negative number to end the loop"); int next = keyboard.nextInt(); int sum = 0; while (next >= 0) { sum = sum + next; System.out.println(sum); System.out.print("Enter a number: "); next = keyboard.nextInt(); }

Using a DEBUG flag Use a DEBUG flag to disable the tracing of variables when no longer needed final boolean DEBUG = true; if(DEBUG) { //print the values of variables }

Automatic Tracing Use a debugger jGRASP provides an integrated debugger Allows you to “step” through your program to see how variables change with each line of code

Programming Demo Hand-shaking problem Given a group of n people, everyone shakes hands with everyone else How many handshakes?

Programming Demo Example, n = 4 6 handshakes Person 1 shakes hands with Person 2 Person 1 shakes hands with Person 3 Person 1 shakes hands with Person 4 Person 2 shakes hands with Person 3 Person 2 shakes hands with Person 4 Person 3 shakes hands with Person 4 6 handshakes

Programming Demo Example, n = 4 6 handshakes Person 1 shakes hands with Person 2 shakes hands with Person 3 shakes hands with Person 4 Person 2 shakes hands with Person 3 Person 3 shakes hands with Person 4 6 handshakes

Handshake Problem n = 6 1 2 3 4 5 6 X

Programming Demo Implementation using nested loops

Friday Recitation Bring Laptops (fully charged) Questions about Program 2