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.

Slides:



Advertisements
Similar presentations
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Advertisements

Week 5 - Friday.  What did we talk about last time?  Repetition  while loops.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Repeating Actions While and For Loops
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
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.
* 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 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.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
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.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
CS101 Computer Programming I Chapter 4 Extra Examples.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Week 6 - Monday.  What did we talk about last time?  while loop examples  Lab 5.
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
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.
Chapter 7: Repetition Structure (Loop) Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
Lab 4: Loops and Iteration Graham Northup
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Lecture 6 Repetition Richard Gesick.
Loop Structures.
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.
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
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.
Chapter 4 Control structures and Loops
Lecture 4A Repetition Richard Gesick.
Looping and Repetition
Outline Altering flow of control Boolean expressions
Lesson #5 Repetition and Loops.
Introduction to Object-Oriented Programming with Java--Wu
Java Programming Loops
Module 4 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6: Repetition Statements
Loop Strategies Repetition Playbook.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Repetition Statements (Loops) - 2
PROGRAM FLOWCHART Iteration Statements.
Announcements Lab 3 was due today Assignment 2 due next Wednesday
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Week 5 - Friday CS 121.
Presentation transcript:

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 can be solved with a computer  Repetition leverages the most famous ability of the computer: speed 2

 The main way that repetition works in Java is through loops  A loop is a block of code that will be executed repeatedly some number of times (perhaps even zero times!)  As the statements are executed, variables may change  It isn’t just repeating the same thing over and over 3

 The simplest loop in Java is the while loop  It looks similar to an if statement  The difference is that, when you get to the end of the while loop, it jumps back to the top  If the condition in the while loop is still true, it executes the body of the loop again 4

while( condition ) { statement1; statement2; … statementn; } A whole bunch of statements 5

 A while loop will usually have multiple statements in its body  However, it is possible to make a while loop with only a single statement  Then, like an if -statement, the braces are optional while( condition ) statement; 6

 Let’s print the numbers from 1 to 100 int i = 1; while( i <= 100 ) { System.out.println(i); i++; } 7

 The while loop checks if the condition is true, and if so, executes each statement one by one  When execution gets to the bottom, it jumps back up to the top  If the condition is still true (i.e., i <= 100 ), it repeats the loop 8

//line A while( condition ) { //line B statement1; statement2; //line C … statementn; } //line D LineCondition An B C D LineCondition AUnknown B C D LineCondition AUnknown BTrue C D LineCondition AUnknown BTrue CUnknown D LineCondition AUnknown BTrue CUnknown DFalse 9

 We can also use while loops to help us deal with input  What if we wanted to sum all of the numbers that a person entered?  How would we know when to stop?  One solution is to keep adding numbers until the person enters a negative number  This is called using a sentinel value 10

 Solution: int i = 0; int sum = 0; while( i >= 0 ) { sum += i; System.out.print(“Enter number: “); i = StdIn.readInt(); } System.out.println(“Sum: “ + sum); 11

 We could also find the average: 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)); 12

 What if we wanted to find the biggest input?  Somehow we would have to check each input and see if it were larger than the current largest  Solution: use an if -statement inside of a while loop  if (i > iBig) iBig = i; 13

 Let’s say that you wanted to write a program to guess a number that a person had come up  The number is between 1 and 100  Every time the computer guesses a number, the person enters:  H if the number is too high  L if the number is too low  F if the number was found 14

1. Start with the minimum and maximum of the range 2. Find the midpoint 3. Ask the user if the midpoint is correct 4. If the answer is too high, go to Step 1 using the minimum and the midpoint as the new range 5. If the answer is too low, go to Step 1 using the midpoint and the maximum as the new range 6. If the midpoint is correct, you’re done! 15

 Just as with if -statements, it’s possible to nest loops  A repetitive task can be done inside of another repetitive task 16

17

 Loops can go on forever if you aren’t careful int n = 40; int i = 1; while( i <= n ) { System.out.println(i); //supposed to print all the numbers //less than 40, but i never increases } 18

int n = 40; int i = 1; while( i <= n ) { System.out.println(i); i--; //woops, should have been i++ } 19

 Being off by one is a very common loop error int n = 40; int i = 1; while( i < n ) //won’t //reach n { System.out.println(i); i++; } 20

 If the condition isn’t true to begin with, the loop will just be skipped int n = 40; int i = 1; while( i >= n ) //oops, should be <= { System.out.println(i); i++; } 21

 A misplaced semicolon can cause an empty loop body to be executed (often infinitely) int n = 40; int i = 1; while( i <= n ); //semicolon is wrong { System.out.println(i); i++; } 22

1. while loops  Used when you don’t know how many times you are going to need to repeat 2. for loops  Used when you do know how many times you are going to repeat 3. do-while loops  Used almost never  Oh, okay, they are used whenever you need to be guaranteed the loop runs at least once 23

 Any problem that uses loops can use any kind of loop  The choice is supposed to make things easier on the programmer  Some loops are more convenient for certain kinds of problems 24

 for loops are great when you know how many times a loop will run  They are the most commonly used of all loops  They are perfect for any task that needs to run, say, 100 times  A for loop has 3 parts in its header: 1. Initialization 2. Condition 3. Increment 25

Way to Progress Ending Point Starting Point for( init; condition; inc ) { statement1; statement2; … statementn; } 26

 A for loop will usually have multiple statements in its body  However, it is possible to make a for loop with only a single statement  Then, like if -statements and while -loops, the braces are optional for( init; condition; inc ) statement; 27

 Let’s print the numbers from 1 to 100 (again)  Remember how this was done with while : i = 1; while( i <= 100 ) { System.out.println(i); i++; } 28

 A for loop is specifically designed for this sort of thing:  The initialization and the increment are built- in for( i = 1; i <= 100; i++ ) { System.out.println(i); } 29

 To see if a number is prime, we can divide by all the numbers less than the number to see if it can be evenly divided  Sounds like a perfect opportunity for a for loop 30

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

 By adding a boolean, we can keep track of whether or not the number is prime int number = StdIn.readInt(); boolean prime = true; for( int i = 2; i < number && prime; i++) { if( number % i == 0 ) prime = false; } 32

 They work just like while loops  The only difference is that they are guaranteed to execute at least once  Unlike a while loop, the condition isn’t checked the first time you go into the loop  Sometimes this is especially useful for getting input from the user  The syntax is a little bit different 33

do { statement1; statement2; … statementn; } while( condition ); 34

 Almost all of these are issues with while, for and do-while loops as well  Many of these errors have to do with incorrect starting or ending conditions for the loop 35

 Loops can go on forever if you aren’t careful int n = 40; int i = 1; do { System.out.println(i); //supposed to print all the numbers //less than 40, but i never increases } while( i <= n ); 36

for( int i = 0; i < 10; i++ ) { System.out.println(i); //lots of other code i--; //woops } 37

int i; for( i = 1; i <= 40; i-- ) //woops, should have been i++ System.out.println(i); 38

 Being off by one is a very common loop error int i; for( i = 1; i < 40; i++ ) //runs 39 times System.out.println(i); 39

 If the condition isn’t true to begin with, the loop will just be skipped for( int i = 1; i >= 40; i++ ) //oops, should be <= System.out.println(i); 40

 A misplaced semicolon can cause an empty loop body to be executed  Everything looks good, loop even terminates  But, only one number will be printed: 41 for( int i = 1; i <= 40; i++ ); //semicolon is wrong { System.out.println(i); } 41