Chapter 6 – Lots of Loops! September 28, 2010. Boolean expression Loop body.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Looping Yong Choi School of Business CSU, Bakersfield.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Introduction to Computer Programming in c
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
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.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
Chapter 5 Loops.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Chapter 4: Control Structures II
Repetition Statements while and do while loops
Chapter 5: Control Structures II
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
ITERATIVE STATEMENTS. Definition Iterative statements (loops) allow a set of instruction to be executed or performed several until condition are met.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
©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.
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 5: Looping. Using the while Loop Loop – A structure that allows repeated execution of a block of statements Loop body – A block of statements.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
The switch Statement, and Introduction to Looping
Chapter 5: Control Structures II
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Learning About the Loop Structure (continued)
Chapter 6 – Lots of Loops! September 28, 2010.
Chapter 5 Repetition.
Outline Altering flow of control Boolean expressions
Chapter 4: Loops and Files
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises UTPA – Fall 2012 This set of slides is revised from.
CHAPTER 21 LOOPS 1.
Repetition Statements (Loops) - 2
Learning Plan 4 Looping.
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.
Control Statements:.
Presentation transcript:

Chapter 6 – Lots of Loops! September 28, 2010

Boolean expression Loop body

Three types of loops A while loop, in which the loop- controlling Boolean expression is the first statement in the loop A for loop, which is usually used as a concise format in which to execute loops A do…while loop, in which the loop- controlling Boolean expression is the last statement in the loop

USING THE while LOOP While(Boolean expression)…. Boolean expression must involve a ‘loop control variable’ Loop control variable must be incremented/decremented somewhere within the loop Otherwise, the loop may be ‘infinite’ meaning incapable of being exited

Loop control variable Can also be set by invoking a user to establish a value for it Can be of almost any data type

Int val = 1; While(val<11) { System.out.println(val); val = val + 1; }

Infinite Loops While(4>2) System.out.println(“Hello”);

How many times does “Hello” get printed here?? loopCount = 1; While(loopCount<3) { System.out.println(“Hello”); loopCount = loopCount + 1; }

How many times does “Hello” get printed here?? loopCount = 1; While(loopCount<3) System.out.println(“Hello”); loopCount = loopCount + 1;

How many times does “Hello” get printed here?? loopCount = 1; While(loopCount<=3); { System.out.println(“Hello”); loopCount = loopCount + 1; }

How many times does “Hello” get printed here?? loopCount = 3; While(loopCount>1) { System.out.println(“Hello”); loopCount = loopCount - 1; }

Using a while loop to control an indefinite loop An indefinite loop is one that is controlled by user input—you don’t know how many times it will execute

import javax.swing.JOptionPane; public class BankBalance { public static void main(String[] args) { int selection; String balanceString; double balance; int tempBalance; int year = 1; final double INT_RATE = 0.03; balanceString = JOptionPane.showInputDialog(null, "Enter initial bank balance"); balance = Double.parseDouble(balanceString);

selection = JOptionPane.showConfirmDialog(null, "Do you want to see next year’s balance?"); while(selection == JOptionPane.YES_OPTION) { balance = balance + balance * INT_RATE; // Note: the next two statements round the balance tempBalance = (int)(balance * 100); balance = tempBalance / 100.0; selection = JOptionPane.showConfirmDialog(null, "After " + year + " years at " + INT_RATE + " interest rate, balance is $" + balance + "\nDo you want to see the balance at the end " + "\nof another year?"); year = year + 1; } System.exit(0); }

while(selection == JOptionPane.YES_OPTION) If the user selects any option other than Yes, the loop body never executes and the next statement to execute is the System.exit(0) If the user selects Yes, all five statements in the loop body execute

When to use indefinite loops.. Programmers use indefinite loops when validating data Validating data is the process of ensuring that a value falls within a specified range

Import javax.swing.*; Public class EnterSmallValue { public static void main(string[] args) { int userEntry; String userString; userString = JOptionPane.showInputDialog(null,”Please enter an integer no higher than 3”); userEntry = Integer.parseInt(userString); while(userEntry > 3) { userString = JOptionPane.showInputDialog(null,”The number you entered was too high\n” + “Please enter an integer no higher than 3”); userEntry = Integer.parseInt(userString); } JOptionPane.showMessageDialog(null, “You entered “ + userEntry); Syste.exit(0); }

Using shortcut Arithmetic Operators int value; value = 24; ++value; // Result – value is 25 value = 24; value++; // Result – value is 25 value = 24; value = value + 1; //Result – value is 25 Value = 24; Value += 1; // Result – value is 25

Prefix and postfix increment operators These are unary operators, meaning that they operate on a single operand Prefix: ++a; Postfix: a++; In prefix, the variable is incremented and then used In postfix, the variable is used and then incremented

Examples of prefix and postfix int a = 1, b; b = ++a; Here, both b and a end up with the value 2 stored within them Int c = 1, d; d = c++; Here, d winds up as 1 and c as 2

Using a for Loop The for loop is used when a definite number of loop iterations is required Following the for is an opening ( followed by three sections separated by semicolons and then a closing )

Three sections in parentheses Initializing the loop control variable Testing the loop control variable This must be a Boolean Expression If the Boolean Expression is true, the body of the loop is entered and executed if the Boolean Expression evaluates to false, control passes to the first executable statement following the loop body Updating the loop control variable

For(int val = 1; val < 11; ++val) System.out.println(val); Does the same thing as….. int val = 1; while(val<11) { System.out.println(val); val = val + 1; }

Permissible For() statements—all of these are for(g=0,h=1;g<6;++g) for(g=0;g 1;++g) for(g=5;g>=1;--g) for(;x<10;++x)

for loops The test is applied at the beginning of the loop

THE do…while LOOP The test is applied at the end of the loop Checks the value of the loop control variable at the bottom of the loop after one repetition has occurred—will always go through the body of the loop at least once

Loop body Test of loop control variable False True

You can nest loops for(customer = 1; customer <= 20; ++customer) for(label = 1; label <= 3; ++label) printlabelMethod(); Or…printlabelMethod(customer, label);

import javax.swing.JOptionPane; public class BankBalanceVaryingInterest { public static void main(String[] args) { int selection; String balanceString; double balance; int tempBalance; int year = 1; double interest; balanceString = JOptionPane.showInputDialog(null, "Enter initial bank balance"); balance = Double.parseDouble(balanceString); selection = JOptionPane.showConfirmDialog(null, "Do you want to see next year’s balance?"); while(selection == JOptionPane.YES_OPTION) {

for(interest = 0.02; interest <= 0.05; interest += 0.01) { balance = balance + balance * interest; tempBalance = (int)(balance * 100); balance = tempBalance / 100.0; JOptionPane.showMessageDialog(null, "After " + year + " years at " + interest + " interest rate, balance is $" + balance); } selection = JOptionPane.showConfirmDialog(null, "Do you want to see the balance at the end " + "\nof another year?"); year = year + 1; } System.exit(0); }

public class IncrementDemo { public static void main(String[] args) { int myNumber, answer; myNumber = 17; answer = ++myNumber; System.out.println ("When myNumber is initialized to 17 and answer = ++myNumber"); System.out.println(" myNumber is " + myNumber); System.out.println(" and answer is " + answer); myNumber = 17; answer = myNumber++; System.out.println ("When myNumber is initialized to 17 and answer = myNumber++"); System.out.println(" myNumber is " + myNumber); System.out.println(" and answer is " + answer); }