CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.

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

Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
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
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
The switch Statement, DecimalFormat, and Introduction to Looping
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
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”);
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
CPS120 Introduction to Computer Science Iteration (Looping)
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Controlling Execution Dong Shao, Nanjing Unviersity.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
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,
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Chapter 5: Structured Programming
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
© The McGraw-Hill Companies, 2006 Chapter 3 Iteration.
Fundamental Programming Fundamental Programming More on Repetition.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
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.
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.
Chapter 7: Repetition Structure (Loop) Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
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.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
The switch Statement, and Introduction to Looping
Quick Test What do you mean by pre-test and post-test loops in C?
CiS 260: App Dev I Chapter 4: Control Structures II.
Looping and Repetition
Outline Altering flow of control Boolean expressions
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Computing Fundamentals
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
CSC215 Lecture Control Flow.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Presentation transcript:

CMP-MX21: Lecture 5 Repetitions Steve Hordley

Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition using the for construct

A problem The calculator program we developed in the previous lectures allows us to perform a single operation on two numbers. We would like to extend the program so that we can repeatedly perform operations on different numbers until the user decides to exit the program. Here, the problem we must address is how we can repeat a set of instructions two or more times. In this lecture we will look at three different JAVA constructs which help us solve this task.

Designing a solution 1. Read two numbers from the keyboard 2. Read an “operation” from the keyboard 3. Apply the operation to the two numbers 4. Write out the result 5. Ask the user if they wish to continue 6. If answer is yes, goto step 1, otherwise stop The basic elements of our program will not change very much: it is still performing the same basic operations, but multiple times. The modified program flow will be something like this:

Designing a solution The program flow can be visualised like this:... statements;... Evaluate expression statements; expression false

The do-while construct In JAVA, this program flow is achieved with the do-while construct:... do{ statements; } while (expression);... The do keyword denotes the start of a block of statements which might be repeated Statements after the do are performed When the while keyword is reached expression is evaluated If expression is true, the program returns to the first statement after the do Otherwise, execution continues after the while

An example... do{ char theAnswer; // Read two numbers // Read an operator // Perform the operation and display the result System.out.println(“Another operation [y/n]?”); theAnswer = Keyboard.readChar(); } while (theAnswer == ‘y’);... We can modify our calculator program to allow multiple operations using a do-while construct:

Some notes If we want to repeat only a single statement we don’t need the curly brackets:... do statement; while (expression);... Once we have more than a single statement between the do and the while, then curly brackets are required.

Other repetition constructs The statements between the do and the while in the do-while construct are always executed at least once This is because the test for repetition (the while (expression) ) comes after the block of statements Sometimes, we want to repeat a block of statements zero or more times depending on some condition. In this case we need the test before the statement block...

The while construct The while construct allows us to deal with this situation:... while (expression){ statements; }... When the while keyword is reached, expression is evaluated If expression is true, the statements between the curly brackets are executed and the program then returns to the while statement Otherwise, program execution continues after the closing bracket

An example... System.out.println(“Perform an operation [y/n]?”); theAnswer = Keyboard.readChar(); while (theAnswer == ‘y’) { // Read two numbers // Read an operator // Perform the operation and display the result }... We can modify the calculator program so that it asks whether an operation is to be performed, each time, including the first:

Some notes The while construct does not have a do associated with it The expression in both the while and the do-while construct must return a boolean value ( true or false ) In both constructs we should take care to choose the expression carefully (and write it correctly) otherwise problems may result

Some common errors int i=1; while (i<4){ System.out.println(“i=1”+i); } The expression in this control loop will always evaluate to true. The result is that the program runs until the computer runs out of memory (or possibly forever): i = 1 … stack overflow…

Some common errors int i=0; while (i>0){ System.out.println(“i=1”+i++); } The expression in this control loop will always evaluate to false so the statement in the loop will never be executed.

The for construct The two loop constructs seen so far execute a set of statements some variable number of times. Sometimes we know in advance how many times we wish to execute a set of statements. JAVA provides a third construct: the for construct for these situations

The for construct... for (initialiser; condition; change){ statements; }... The for construct has the following general form: An expression evaluated once, when the for is first encountered An expression evaluated before each cycle of the loop An expression evaluated at the end of each cycle of the loop

The for construct The for has the following flow: initialiser Evaluate “condition” execute loop statements Evaluate “change” Next program statement true false

An example... for (int i=0; i<4; i++){ System.out.println(“i=“+i); }... i=0 i=1 i=2 i=3 Outputs:

The for loop int i=0; while (i<4){ System.out.println(“i=“+i); i++; } We can re-write any for loop as a while construct. E.g. the previous example: Initialisation is performed first Condition is tested If condition is true, statements are performed Change expression is evaluated

A second example Suppose we wish to calculate x n ( x to the power of n ). This can be done with the following for construct: for (r=1.0, i=1; i<=n; i++) r*=x; In this example, two initialisations are performed: r=1.0 and i=1. Multiple initialisations are separated by commas Any of the three parts of the for can have multiple expressions. These expressions must be separated by a comma.

A second example for (r=1.0, i=1; i<=n; i++, r*=x) ; In this case no statement is executed after the for. This is denoted by the semi-colon on its own. The previous example could also be written like this:

Some notes Any of the initialisation, condition, and change can be omitted from the for : r=1.0; i=1; for (; i<=n; i++, r*=x) ; Note that the semi-colon separating these three elements must remain: all for constructs have two semi-colons

Some notes for (;;) System.out.println(“This loops for ever”); We can even leave all three elements out of the construct: Note, if there is no condition, it will be regarded as true So, if our for loop doesn’t contain a condition we need an alternative method to terminate the loop

Terminating loops The break statement can be used to terminate a loop: for (i=1;;){ System.out.println(“i=”+i++); if (i==5) break; } The break statement causes program execution to jump to the first statement after the end of the loop The break statement can be used in a for, a do-while, or a while construct

Terminating loops The continue statement causes program execution to jump to the beginning of the next loop: for (i=1;i<=5;i++){ if (i==3) continue; System.out.println(“i=”+i++); } i=1 i=2 i=4 i=5

Some common errors for (i=1;i<=5;i++); System.out.println(“i=”+i++); i=6 Putting a semi-colon at the end of the for statement means that no statements are to be executed at each loop. The change expression and the condition are still evaluated until the condition becomes false Then the statements after the for will be executed

Some common errors Like the do-while and while loops, we need to be careful with the condition statement in a for loop: for (i=10;i<=5;i--) System.out.println(“i=”+i++); Here the condition is false from the start so the loop never gets executed

Some common errors for (i=10;i>5;i++) System.out.println(“i=”+i++); i=10 i=11 i=12... stack overflow error Here the condition is always true so the loop will continue until the system runs out of resources (or forever)

A summary In this lecture we have introduced three JAVA constructs for repetition: the while, the do-while, and the for We have also seen how to exit from program loops using the break and continue statements

A summary You should now be familiar with the meaning of the following words from the JAVA language: do, while, for, continue, break