1 CS 177 Week 5 Recitation Slides Loops. 2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Advertisements

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.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
Copyright 2008 by Pearson Education 1 Midterm announcements Next week on Friday May 8 Must bring an ID Open book, open notes, closed electronics Must attend.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
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.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Java Programming: From the Ground Up
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Chapter 5 Loops.
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.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CS101 Computer Programming I Chapter 4 Extra Examples.
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.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Repetition Statements while and do while loops
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Week 6 - Monday.  What did we talk about last time?  while loop examples  Lab 5.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING While Loop.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
©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.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
Lecture 4b Repeating With Loops
Lecture 6 Repetition Richard Gesick.
Control Structures.
Chapter 5: Control Structures II
Loop Structures.
Lecture 4A Repetition Richard Gesick.
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
PROGRAM FLOWCHART Iteration Statements.
Building Java Programs
Announcements Lab 3 was due today Assignment 2 due next Wednesday
Looping Structures.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

1 CS 177 Week 5 Recitation Slides Loops

2 Announcements Project 2 due next Thursday at 9PM. Exam 1 this evening (switch and loop not covered) Old exams posted

3 QUESTIONS???

While Loops Uses repetition to perform a lot of work very fast They look a lot like if statements: 4 int x = 0; if(x < 5) { /*do work using statements*/ } int x = 0; while(x < 5) { /*do work using statements*/ } When here, finished When here, loop back up And test again… x += 1; Need to assure a statement is in place to cause the expression to eventually evaluate to false

While Braces are optional for a single statement while (i < 10) sum += i++; As with ifs, only when the expression is true will the statements within the while block be executed. The big difference is that when the last statement of a while is executed (if the expression was first true), the expression will be re-evaluated. 5  MUST BE CAREFUL that the condition will depend on a value that changes as the loop progresses or a “break” will be needed (to be discussed).

Small contrived example boolean value = true; //program statements… while (value) { System.out.println(“If here, value is true!”); value = false; System.out.println(“value can change…”) System.out.println(“But ONLY matters at the end”); value = true; } 6 With value set to true in the end it will loop forever

boolean value = true; //program statements… int count = 0; while (value) { System.out.println(“If here, value is true!”); value = false; //… lots of work value = true; count++; } 7 if (count > 10) value = false; This causes the loop to stop… After how many iterations??? i.e. how many times will If here, value is true! print?

Keep multiplying input numbers until a sentinel reached 8 int i = 1; int product = 1; while( i != 0 ) { product *= i; System.out.print(“Enter number: “); i = StdIn.readInt(); } System.out.println(“Product: “ + product); What is the sentinel here? Why is i initialized to 1? So that the while expression will evaluate to true to first enter the loop but also once inside the loop, multiplying by 1 does not affect the final value (as opposed to i = 2).

From lecture: 9 int i = 0; double sum = 0; int count = 0; while( i >= 0 ) { sum += i; count++; System.out.print(“Enter number: “); i = StdIn.readInt(); } count--; //fixes extra count for sentinel System.out.println(“Average: “ + (sum/count)); Getting the sentinel value counted as1 input, so, just calculate with (count-1) to calculate with just the actual values +(sum/(count-1)));

Infinite Loops  int i = 0; int sum = 0; while(i <= 10) { sum += i; } 10 This loop will run forever! WHY??? How do we fix this? i++; This run-time error is a little harder to make when using for loops…

for loops for(init; condition; inc) { //statements } 11 init; //statement while(condition) { //statements inc; //statement } Without increment statements, loops can run forever (unless there is a break… to-be-discussed) but with for loops, you add it right at the beginning.

Side by Side 12 int i = 0; int sum = 0; while(i <= 10) { sum += i; i++; } int sum = 0; for(int i = 0; i <= 10; i++) { sum += i; }

for loops cont. 13 int sum = 0; for(int i = 0; i <= 10; i++) { sum += i; } init performed once only at beginning of loop. condition is checked at the beginning and before each next loop iteration inc is performed at the end of every loop iteration just before condition is rechecked

Another Painful Error for Both while and for Loops int i = 0; int sum = 0; while(i <= 10); { sum += i; i++; } 14 int sum = 0; for(int i = 0; i <= 10; i++); { sum += i; } Semicolons placed here will give you a not-so-expected result!! What will happen in the two cases and why??? Will be different for each. For loop will have a compilation error since i is declared inside the loop and i is used “outside” of loop…

What about 15 int sum = 0; int i; for(i = 0; i <= 10; i++); { sum += i; } What will sum and i be here (no error this time…)?

When do we use whiles and when do we use fors? The answer is not EXACTLY clear cut, BUT there is a general use for each that seems natural: 16  for loops are great for “count controlled” loops; i.e. loops that have a count with them. Loops from 1 to 100 for instance  while loops are great for “event controlled” loops; i.e. loops that keep iterating until some event has occurred Loop until program gets correct input for instance

From lecture… The following code will tell you if a number isn’t prime What’s the problem? 17 int number = StdIn.readInt(); for( int i = 2; i < number; i++) { if( number % i == 0 ) { System.out.println(number + “ is not prime.”); }

cont. By adding a boolean, we can keep track of whether or not the number is prime 18 int number = StdIn.readInt(); boolean prime = true; for( int i = 2; i < number && prime; i++) { if( number % i == 0 ) prime = false; } 18 break; Some might think this would work? (and in a way it does…) BUT What about when the loop is finished and we want to know LATER if the number is actually prime without doing the loop again?? ; i++)

do-while Work just like while loops, only execute statements once before ever checking the condition… do { //statements… } while(condition); 19 Note here the semicolon, because it is at the end NOT at the beginning, it denotes the end of the statement.

Get a password/combination String combinationForDruidea; //anyone name the movie? do { System.out.println(“Please enter password:”); combinationForDruidea = StdIn.readString(); } while( !(combinationForDruidea.equals(“1234”) ); //”Amazing, now I’m going to have to change the //combination on my luggage!” 20 If you know the loop will have to execute the statements AT LEAST once, then you can use a do-while loop.

Side by Side for product int product = 1; System.out.print(prompt); int x = StdIn.getInt() while(x != 0) { product *= x; System.out.print(prompt); x = StdIn.getInt(); } 21 int product = 1; int x; do { System.out.print(prompt); x = StdIn.getInt(); product *= x; } while(x != 0) String prompt = “Please enter a number to multiply to the product Enter 0 to quit\n”);

import lejos.nxt.*; public class BasicRobotTest { public static void main(String[] args) { TouchSensor tSensor = new TouchSensor(SensorPort.S1); int x = 3; LCD.drawInt(x, 0, 0); Sound.beep(); pause(1000); LCD.drawString("Touch me to", 0, 0); LCD.drawString("shut me up!", 0, 1); while (!tSensor.isPressed()) { Sound.buzz(); } Motor.A.setSpeed(720); Motor.C.setSpeed(720); Motor.A.forward(); Motor.C.forward(); pause(1000); Motor.A.stop(); Motor.C.stop(); } 22 int x = 3; LCD.drawInt(x, 0, 0); Sound.beep(); pause(1000); LCD.drawString("Touch me to", 0, 0); LCD.drawString("shut me up!", 0, 1); while (!tSensor.isPressed()) { Sound.buzz(); } Motor.A.setSpeed(720); Motor.C.setSpeed(720); Motor.A.forward(); Motor.C.forward(); pause(1000); Motor.A.stop(); Motor.C.stop(); Displays a 3 and beeps for a second Displays “Touch me to shut me up!” Loop to buzz forever UNTIL the sensor is pressed Sets the speed of the motors Tells the motors to move forward at that speed for a second then to stop. Next week’s Lego Lab Starter

Last Bit on Loop Errors BE CAREFUL!!  When using loops, you have to follow the syntax and the logic you want EXACTLY or a lot can go wrong. 23 If you have a loop and the program just seems to sit there, you may have an infinite loop.  Infinite Loops can be caused for various reasons… In cases, your value can be off by 1 if you’re not careful. Sometimes, a condition can look right but is actually wrong, a loop may never execute… And the misplaced semicolon can make life miserable!

Infinite Loops int x = 0; do { System.out.println(x); }while(x < 10) 24 for(int x = 0; x < 10; x++) { System.out.println(x); /*code that make you feel you’ve accomplished something */ x--; //even more code } How would we fix either? What about? x--

Off by 1 int ranThrough = 0; for(int i = 1; i < 40; i++) { System.out.println(i); ranThrough++; } System.out.println(“The loop ran through “ + ranThrough + “ times”); 25 What will print here? What will be the printed value of i on the LAST print statement? ranThrough is 39!

Problems? for(int i = 1; i >= 40; i++) System.out.println(i); 26 This will never print anything…. WHY? Looks right but a logic problem with expression… int i; for(i = 1; i <= 40; i++); System.out.println(i); What is the problem? What will actually print and how many times? for(int i = 1; i <= 40; i++); System.out.println(i); //gives compilation error! //i used “outside” loop //where it was declared.

27 Final QUESTIONS???