CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Repeating Actions While and For 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.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
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.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
The switch Statement, DecimalFormat, and Introduction to Looping
CS0007: Introduction to Computer Programming Introduction to Arrays.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
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.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 4: Loops and Files
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 4: Control Structures II
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Lecture 3 Looping and FIiling. 5-2 Topics – The Increment and Decrement Operators – The while Loop – Using the while Loop for Input Validation – The do.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 5A Repetition (Concepts)
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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.
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING While Loop.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
The switch Statement, and Introduction to Looping
Yanal Alahmad Java Workshop Yanal Alahmad
Loop Structures.
Lecture 4- Loops and Files
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.
Chapter 5: Repetition Structures
Repetition-Counter control Loop
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Chapter 4: Loops and Files
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
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.
Presentation transcript:

CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class

Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1: //One or more statements break; case CaseExpression2: //One or more statements break; default: //One or more statements } CaseExpression s must be of type… char, byte, short, or int.

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 a statement or group of statements to repeat. Two looping structures talked about so far… while Loop do - while Loop The difference between the two… while Loop is pretest do - while Loop posttest

The for Loop You can do any kind of looping with what we learned up to this point. For instance, how can we make a do - while loop without the do - while looping structure? while and do - while are conditionally-controlled loops. A Conditionally-Controlled Loop executes as long as a particular condition exists. However, sometimes you know exactly how many iterations a loop must perform. A loop that repeats a specific number of times is called a count-controlled loop. For example, you may ask for information about the 12 months about a year. You can turn conditionally controlled loops into count-controlled loops, but Java provides a structure specifically for this called the for loop.

The for Loop The for loop has three elements: 1. It must initialize a control variable to a starting value. 2. It must test the control variable to see when the loop terminates. 3. It must update the control variable during each iteration. General Form of a for loop: for(Initialization; Test; Update) Statement or Block Initialization – an initialization expression that happens once when the loop is first reached. Normally used to initialize the control variable Test – boolean expression known as the test expression that controls the execution of the loop. As long as this is true, the loop with iterate again Note: the for loop is a pretest loop Update – expression known as the update expression that executes at the end of every iteration Usually used to change the control variable.

for Loop Flowchart Test Expression Statement or Block True False Update Expression Initialization Expression

The for Loop for(int count = 0; count < 5; count++) System.out.println("Hello!"); This will print “Hello!” 5 times. First, count is initialized to 0. count is often called a counter variable because it keeps count of the number of iterations. Then, count < 5 is tested. It is true so the body is executed. Then, count is incremented. This happens 5 times until count = 5 which makes count < 5 false. Note that count is declared inside of the loop header, this makes it have block-level scope in the loop. This implies that it can be used in the body of the loop. The counter variable can be declared outside of the header.

for Loop Example public class ForLoop { public static void main(String[] args) { for(int number = 1; number <= 10; number++) { System.out.println(number + "\t\t" + number*number); }

The for Loop Notes Remember: the for loop is a pretest loop. Use the update expression to modify the control variable, not a statement in the body of the loop (unless there is no way to avoid it) You can use any statement as the update expression: count-- count += 2 You can declare the loop control variable outside of the loop header, and it’s scope will not be limited to the loop. int count; for(count= 0; count < 5; count++) System.out.println("Hello!"); count = 99;

Prefix and Postfix Increment and Decrement Operators We talked about the ++ and -- operators before x++ x-- These are known as postfix increment and decrement operators, because they are placed after the variable. There is also prefix increment and decrement operators: ++x --x What’s the difference? oWhen the increment or decrement takes place. int x = 1, y; y = x++; y is 1 x is 2. The increment operator happened after the assignment operator. int x = 1, y; y = ++x; y is 2 x is 2. The increment operator happened before the assignment operator.

User-Controlled for Loop import java.util.Scanner; public class UserControlledForLoop { public static void main(String[] args) { int begNum, endNum; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a begining number for the squares table: "); begNum = keyboard.nextInt(); System.out.print("Enter an ending number for the squares table: "); endNum = keyboard.nextInt(); for(int number = begNum; number <= endNum; number++) { System.out.println(number + "\t\t" + number*number); } } }

Multiple Statements in the Initialization and Update Expressions Java allows multiple statements to be executed in the initialization and/or update expression portion of the for loop. Example: MultipleForLoop.java (See Lesson 10 Program Sheet)

Running Totals and Accumulator Variables Programming tasks often require you to keep a running total of some data. This can often be done by looping and keeping track of the running total in a single variable. A variable that keeps track of a running total is called an accumulator variable. Example: AccumulatorVariable.java (See Lesson 10 Program Sheet)

Sentinel Value The previous example required the user to enter in beforehand how many days they sold. We can allow the user to keep entering until they decide to quit by looping until they enter a sentinel value. A Sentinel Value is a special value that cannot be mistaken for normal input that signals that a loop should terminate. We’ve done this before… SoccerLeague.java Example: SentinelValue.java (See Lesson 10 Program Sheet)

Nested Loops Just like in if statements, loops can be nested. This is required when a repetition of statements itself must be repeated a number of times. Example: NestedLoop.java (See Lesson 10 Program Sheet)

break and continue Java provides two keywords that can be used to modify the normal iteration of a loop: break – when encountered in a loop, the loop stops and the program execution jumps to the statement immediately following the loop. continue – when encountered in a loop, the current iteration of the loop stops immediately. Example: BreakAndContinue.java (See Lesson 10 Program Sheet)

The Random Class Some application require randomly generated numbers The Java API provides a class called Random that does exactly that. Need to import it: import java.util.Random; To create an object: Random identifier = new Random(); The random class provides many methods for generating random numbers, namely: nextDouble() – Returns the next random number as a double between 0.0 and 1.0. nextInt() – Returns the next random number as an int within in the range of int (-2,147,483,648 to 2,147,483,648) nextInt(int n) - Returns the next random number as an int within in the range of 0 and n.

Random Class Example (See Lesson 10 Program Sheet)