PHY281 Scientific Java Programming LoopsSlide 1 Loops In this section we will learn how to repeat a series of instructions using loops and to use this.

Slides:



Advertisements
Similar presentations
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.
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Computer Science 1620 Loops.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
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.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
OOP&M - laboratory lectures1 OOP&M – LAB3 LABtres: drawing.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
More loops Linag, Chpt 3, pp The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition? loop-body.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Loop Statements (Iteration). Iteration  A portion of a program that repeats a statement or group of statements is called a loop.  Each repetition of.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
5.05 Apply Looping Structures
1 Web Based Programming Section 6 James King 12 August 2003.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #005 (April somthin, 2015)
Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
CPS120 Introduction to Computer Science Iteration (Looping)
Loops and Iteration for Statements, while Statements and do-while Statements.
Chapter 4 C Program Control. Objectives In this chapter, you will learn: –To be able to use the for and do … while repetition statements. –To understand.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
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.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Computer Science Department LOOPS. Computer Science Department Loops Loops Cause a section of your program to be repeated a certain number of times. The.
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,
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
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.
1 Programming Week 2 2 Inheritance Basic Java Language Section.
Chapter 5: Control Structures II
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CPS120 Introduction to Computer Science Iteration (Looping)
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Loops and Files. 5.1 The Increment and Decrement Operators.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Fundamental Programming Fundamental Programming More on Repetition.
Controlling Program Flow with Decision Structures.
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 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
COP 2220 Computer Science I Topics –Breaking Problems Down –Functions –User-defined Functions –Calling Functions –Variable Scope Lecture 4.
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 
PHY 107 – Programming For Science. Today’s Goal  How to use while & do / while loops in code  Know & explain when use of either loop preferable  Understand.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
UCT Department of Computer Science Computer Science 1015F Iteration
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
Java Programming: Guided Learning with Early Objects
Incrementing ITP © Ron Poet Lecture 8.
Looping and Repetition
Outline Altering flow of control Boolean expressions
Repetition Statements (Loops) - 2
Java LESSON 3 Loops.
Looping and Repetition
Presentation transcript:

PHY281 Scientific Java Programming LoopsSlide 1 Loops In this section we will learn how to repeat a series of instructions using loops and to use this to do animation:  while Loops  for Loops  Infinite Loops  do... while Loops  Exiting Loops  Animation

PHY281 Scientific Java Programming LoopsSlide 2 while Loops One of the simplest loops is the while Loop. This keeps looping as long as the test condition is true. while ( ) { } The real power of computers is their ability to do the same or similar things many many times. For this you need loops. Test the condition Body of the loop True False int n = 0; int sum = 0; while (n < 20) { sum = sum + n; n++; } The loop does not necessarily execute at all if the test condition is never met.

PHY281 Scientific Java Programming LoopsSlide 3 Parallel Lines import java.awt.*; import java.applet.*; public class Lines extends Applet { public void paint(Graphics g) { int n = 0; int x = 20; int y = 20; while (n < 20) { g.drawLine(x, y, x + 200, y); y = y + 10; n++; } Test counter Increment counter Initialise counter Loop

PHY281 Scientific Java Programming LoopsSlide 4 for Loops The most powerful loop is the for Loop. for ( ; ; ) { } Test the condition Body of the loop True False Change Initialise The loop does not necessarily execute at all if the test condition is never met. int sum = 0; for (int n=0; n<20; n++) { sum = sum + n; }

PHY281 Scientific Java Programming LoopsSlide 5 A Grid of Lines import java.awt.*; import java.applet.*; public class Grid extends Applet { public void paint(Graphics g) { int x = 20; int y = 20; for (int i=0; i<=10; i++) { g.drawLine(x, y, x + 100, y); y = y + 10; } y = 20; for (int i=0; i<=10; i++) { g.drawLine(x, y, x, y + 100); x = x + 10; } Test counter Increment counter Initialise counter Loop Reset y

PHY281 Scientific Java Programming LoopsSlide 6 The scope of the counter for (int i=1; i<=10; i++) { g.drawString("i = " + i, 50, i*10); sum += i; } g.drawString("Sum = " + sum, 50, 120); g.drawString("i = " + i, 50, 130); i is declared in the loop Normally the counter is declared inside the loop - and cannot be used outside (this is known as the scope of a variable). this gives an error as i is undeclared outside the loop int i; for (i=1; i<=10; i++) { g.drawString("i = " + i, 50, i*10); sum += i; } g.drawString("Sum = " + sum, 50, 120); g.drawString("i = " + i, 50, 130); i is declared outside the loop this is now OK (i would be 11)

PHY281 Scientific Java Programming LoopsSlide 7 Infinite Loops If you are not careful you can get the program into an infinite loop that go round for ever and are hard to break out of. These all generate infinite loops: for (;;) { g.drawString("looping", 50, 50); } for (int i=1;i<=10;) { g.drawString("looping", 50, 50); } for (int i=1;i>0;i++) { g.drawString("looping", 50,50); } left out the increment test is always true nothing in here

PHY281 Scientific Java Programming LoopsSlide 8 Floating Point Counters You may not want the loop counter to increment by integer values. It is perfectly legal to have a floating point loop counter but is usually undesirable. The reason is rounding errors. Because floating point numbers are not stored exactly as you add the increment the number can start to deviate from what you want. It is much better to use an integer loop counter and convert it. public class Floop extends Applet { public void paint(Graphics g) { int x = 20; int y = 20; for (double d=0.0; d<=1.0; d+=0.1) { g.drawString("d = " + d, x, y); y = y + 10; } for (int i=0; i<=10; i++) { double d = i/10.0; g.drawString("i = " + i + " d = " + d, x, y); y = y + 10; } d is not always exactly what you want i is always exactly what you want i is converted into d each time so errors don't accumulate

PHY281 Scientific Java Programming LoopsSlide 9 do... while Loops A very similar loop to the while loop is the do... while Loop. The only difference between this and the while Loop is that the conditional test is at the end. do { } while ( ) ; int sum = 0; int i = 1; do { sum += i; i++; } while (i <= 10); Unlike the while Loop the do... while Loop is guaranteed to loop at least once even if the test always fails. Test the condition Body of the loop True False

PHY281 Scientific Java Programming LoopsSlide 10 Fibonacci Series public class Fibonacci extends Applet { public void paint(Graphics g) { int x = 10; int y = 20; int iprev = 0; int ilast = 1; int inext = 1; g.drawString(" " + inext, x, y); do { g.drawString(" " + inext, x, y); inext = ilast + iprev; iprev = ilast; ilast = inext; x = x + 40; if (x > 200) { x = 10; y = y + 20; } } while (inext < 1000); } The Fibonacci Series is the series of numbers: where each number (except the first two) is the sum of the previous two numbers. This program prints the Fibonacci series below 1000.

PHY281 Scientific Java Programming LoopsSlide 11 Exiting a Loop Normally you exit a loop when the test condition becomes false. However you might like to stop earlier or skip parts of the loop. You can do this using the break and continue statements. break exits the loop immediately. continue stops the current pass through the loop and starts a new one. while ( ) { if ( ) continue; if ( ) break; } goes to the beginning of the loop again goes to the statement after the loop Can be any sort of loop for, while, do... while.

PHY281 Scientific Java Programming LoopsSlide 12 Animation By using combinations of loops and decisions we can produce animations i.e. produce a picture that changes with time. One key trick is used in animation to give the impression of movement even though in practice nothing actually moves. If you draw an object and want it to appear to move you delete it and draw it somewhere else. If the computer is fast enough it looks like it moves. For a simple object you can delete it by redrawing it in the background colour. The following program simulates a ball bouncing around inside a rectangle. The movement is simulated by redrawing the ball in the background colour. You can get the current background colour using: Color backgroundColour = getBackground(); which is the opposite of setBackground( ). We move the ball around the screen by incrementing the x and y position. When it gets to an edge we have to change the sign of the incrementaion.

PHY281 Scientific Java Programming LoopsSlide 13 Bouncing Ball public class Ball extends Applet { int rectLeft = 50, rectRight = 150; int rectTop = 50, rectBottom = 150; int x = rectLeft + 7; int y = rectTop + 2; int xChange = 2; int yChange = 1; int diameter = 10; public void paint(Graphics g) { continued on next page

PHY281 Scientific Java Programming LoopsSlide 14 Bouncing Ball Continued public void paint(Graphics g) { for (int n=1; n < 1000; n++) { g.setColor(Color.black); g.drawRect (rectLeft, rectTop, rectRight - rectLeft, rectBottom - rectTop); Color backgroundColour = getBackground(); g.setColor(backgroundColour); g.fillOval(x, y, diameter, diameter); if (x <= rectLeft) xChange = -xChange; if (x >= rectRight - diameter) xChange = -xChange; if (y <= rectTop) yChange = -yChange; if (y >= rectBottom - diameter) yChange = -yChange; x = x + xChange; y = y + yChange; g.setColor(Color.red); g.fillOval(x, y, diameter, diameter); } Draw new ball Erase previous ball Draw box

PHY281 Scientific Java Programming LoopsSlide 15 Slowing it down public void paint(Graphics g) { for (int n=1; n < 1000; n++) { for (int i=1; i<500000; i++) { } g.setColor(Color.black);... If the animation is too fast we can slow it down by introducing a second loop inside the first one (this is called nesting) which does nothing except waste a bit of computer time. This number controls the speed of the ball This number controls how long the animation lasts There are better ways of doing this because here the speed of the ball depends on the speed of your computer.

PHY281 Scientific Java Programming LoopsSlide 16 Using sleep import java.util.*;... public void paint(Graphics g) { for (int n=1; n < 1000; n++) { try { Thread.currentThread().sleep(2000); } catch (Exception e){} g.setColor(Color.black);... This number is the time to sleep in milliseconds (2 seconds in this case) If we use the sleep( ) method the program will wait for the time specified before continuing. The time spent sleeping should be independent of the speed of the computer. Unfortunately we have to do some Exception Handling to use it. This means we try to execute what is inside the { } but if it fails for some reason an Exception is thrown. If an Exception is thrown the code inside the { } is executed (which in this case does nothing). Otherwise the program would crash. This just means this bit of the program