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”);

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.
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
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 © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
The switch Statement, DecimalFormat, and Introduction to Looping
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
CPS120 Introduction to Computer Science Iteration (Looping)
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
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.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
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.
Lec 4: while loop and do-while loop. Review from last week if Statements if (num < 0.5){...println("heads"); } if –else Statements if (num < 0.5){...println("heads");
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.
Chapter 3- Flow Control. Overview n Why flow control n Branches vs. Loops n Branch statements n Loop Statements n Complex loops n Boolean variables n.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Chapter 5: Control Structures II
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
CPS120 Introduction to Computer Science Iteration (Looping)
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
Week 6 - Monday.  What did we talk about last time?  while loop examples  Lab 5.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
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.
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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.
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.
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
(Java Looping and Conditional Statements). Flow of control Sequential Executes instructions in order Method Calls Transfer control to the methods, then.
Loops A loop is: Java provides three forms for explicit loops:
Chapter 4 Repetition Statements (loops)
Introduction To Repetition The for loop
The switch Statement, and Introduction to Looping
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 5: Control Structures II
Loop Structures.
JavaScript: Control Statements.
Arrays, For loop While loop Do while loop
Looping and Repetition
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Lec 4: while loop and do-while loop
Computing Fundamentals
Looping and Repetition
Presentation transcript:

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”); … It would be tiresome to write out this code over and over, and with enough ‘iterations’ of this code, it would soon be confusing what you’re trying to accomplish.

A loop is a kind of structure that can iterate over the same code multiple times. There are several different loops that Java uses, like while loops, do loops, and for loops. For all loops, there is typically a way to set when a loop stops. These are set differently for each one. Typically, there will be a boolean expression somewhere that has the loop stop when that boolean expression results to false.

Scanner in = new Scanner(System.in) String answer = “yes”; while(!answer.equalsIgnoreCase(“no”)) { //code code code code System.out.println(“Go again? Answer yes or no.”); answer = in.nextString(); }

A while loop starts off with the ‘while’ keyword, followed by a boolean expression in parenthesis. The while loop also has a pair of brackets, just like an if statement. while(myInt1 > myInt2) { … } If the expression in the parenthesis results to true, the loop runs the code inside the brackets that follow. The while loop will continue to run for as long as the running condition is true. The running condition is checked at the beginning of the loop, and again after its code inside the body is executed. Because we set our own conditions for looping, loops are especially great when we don’t know in advance how many times to repeat code.

To put it in a better way, using pseudocode: 1.Check condition 2.If condition = true, go to line 3, otherwise go to line 5. 3.Run loop code 4.Go to line 1 (this is the end of the loop body) 5.Exit the loop

int i = 0; while(i < 4) { System.out.print(“” + i); i++ } The results of this would be: 0123 Once i equals 4 or higher, the loop exits because its running condition is no longer true.

int i = 4; while(i < 4) { System.out.print(“” + i); i++ } The results of this would be: Nothing By the time the loop is reached, i = 4, so the running condition is false and the loop is entirely skipped.

Notice in the previous slide that inside the body of the while loop, we are altering a variable involved in the running condition. If we had not altered ‘i‘, then the running condition would always hold true. Therefore, the loop would run infinitely. Typically, to avoid accidental infinite loops, it is desirable to alter one of the variables of the condition every frame so that it will eventually become false and exit the loop.

Do loops work the same way as while loops, with one exception. Instead of evaluating the looping condition at the beginning like a while loop does, it evaluates it at the end of the body. As such, the loop starts with ‘do’, and ends with ‘while’ and the conditional statement, followed by a semicolon. The program will go through the body of the loop once, and then check the condition to see if it should run again. Therefore, do loops will always run at least once. They are written like so: do { // …code… } while(loopingCondition);//Don’t forget the semicolon!

int i = 0; do { System.out.println(“” + i); i++; } while(i < 0); Result: 0 Even though the do loop condition is false from the beginning, the body of the loop will run at least once because it only checks if its true at the end of the loop.

Consider this piece of code int i = 0; while (i < 4) { System.out.println(“” + i); i++; } Obviously, this would stop at some point.

Now, what would happen if, instead, ‘i‘ decremented every iteration? I would never go up to 4, so the looping condition is always true? However, recall that values have a certain amount of data set to them (say, 4 bytes, for ints) As ‘I’ is constantly decremented, its magnitude (not the value) is getting bigger and bigger because the looping condition never stops. Soon, it gets to a point where the number’s magnitude is so big, it can’t fit into four bytes.

When a number gets to a value that is so big that it can’t fit into the data space it is given, an overflow occurs. In some languages, this generates an error. But it Java, IT DOES NOT. What happens instead is that the number ‘rolls over’ from the largest negative number, over to the largest positive number. This is an effect of how numbers are stored inside memory. In our case, after ‘i‘ rolls over to a very large positive number, the loop condition (i < 4) finally becomes false, and the loop stops on that very large positive number. This is especially important to us, because this does not produce an error, so it may be hard to spot and fix.

It is also possible to write a loop such as: while(true) { …code… } Here, in the running condition, true = true. But of course, we wouldn’t want that because the loop would run infinitely. And just like with overflowing, this does not produce an error. The program would be stuck inside the body of the loop forever. Or until the user closes the application. When you, as a developer, run in to this problem, there is a red square near the console window in Eclipse you could press to terminate your program.

There exists a way to prematurely exit the loop with the ‘break’ keyword. while(true) { …code… break; } The break keyword exits the loop it belongs to as soon as it is reached, regardless of the running condition. However, this design is not recommended, because it doesn’t make it clear from the running condition when the loop is supposed to exit.

In general, loops based on numeric values are based on a test of inequality, where one value or another decreases or increases inside the body of the loop. Consider this: While(x < y) { …increase x by some amount…} Once x goes over y, the loop exits. But this: while(x != y) { …increase x by some amount… } This isn’t recommended to do, since we’re increasing x by ‘some’ amount, and it may completely skip over y.

This would also be unwise: while(myFloat1 != myFloat2) { …increment myFloat1 by something…} In the case of floats and other decimal values, binary representations of two floats may not be exact (even if they’re really close) Recall the possibility of getting a value like instead of 5.0 from doing floating-point arithmetic. This is where using inequality operators like ‘ ’, ‘ =‘ is desirable, because even if we aren’t sure whether two numbers are equal, we can be sure that one number is at least greater than or less than another number.

Recommended guidelines for writing loops: Always use a running condition that will eventually become false. Inside the body of the loop, there should be something that affects one of the running condition variables. It should be incremented, decremented, or set in such a way that it will make the running condition false if it continues running. Be wary of the possibility of overflowing. Overflowing won’t stop the code from running and won’t produce an error. The ‘break’ keyword is there to prematurely exit loops. But this should be avoided for the sake of readability and testing. Prefer using greater than, less than operators when dealing with numbers in the loop condition. Never test for equality.