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

Similar documents
Chapter 4: Loops and Files

Chapter 4: Loops and Files

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Loops. CSE 114, Computer Science 1 Stony Brook University

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Object-Oriented Programming in Java

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

What two elements are usually present for calculating a total of a series of numbers?

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

ECE 122. Engineering Problem Solving with Java

Fundamentals of Programming Data Types & Methods

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Programming with Java

Problem Solving With Loops

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Increment and the While. Class 15

Lesson 7 Part 2 Flags

Repetition. Chapter 6

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition. Chapter 6

CompSci 125 Lecture 11

Chapter 5: Loops and Files

REPETITION CONTROL STRUCTURE LOGO

Top-Down Program Development

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

STUDENT LESSON A12 Iterations

Repetition CSC 121 Fall 2014 Howard Rosenthal

LECTURE 5 Control Structures Part 2

Computer Programming I - Unit 5 Lecture page 1 of 14

Last Class. While loops Infinite loops Loop counters Iterations

AP Programming - Chapter 6 Lecture

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Introduction. C provides two styles of flow control:

Java Coding 3. Over & over again!

Input. Scanner keyboard = new Scanner(System.in); String name;

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

CSC 1051 Data Structures and Algorithms I

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Full file at

Repetition, Looping. While Loop

Anatomy of a Java Program: Comments

AP Computer Science Unit 1. Programs

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

13 th Windsor Regional Secondary School Computer Programming Competition

COMP 202 Java in one week

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

ECE 122 Engineering Problem Solving with Java

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Introduction to Java & Fundamental Data Types

Computational Expression

DELHI PUBLIC SCHOOL TAPI

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

CS111: PROGRAMMING LANGUAGE II

COMP 202. Java in one week

Controls Structure for Repetition


CS1004: Intro to CS in Java, Spring 2005

CSC 1051 Data Structures and Algorithms I

Java I/O and Control Structures

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Section 2.2 Your First Program in Java: Printing a Line of Text

Chapter Goals. Contents LOOPS

Object Oriented Programming. Java-Lecture 6 - Arrays

SFWR ENG/COMP SCI 2S03 Principles of Programming SOLUTIONS

St. Edmund Preparatory High School Brooklyn, NY

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

A token is a sequence of characters not including any whitespace.

Lecture 7 Tao Wang 1

Introduction to the Java Basics: Control Flow Statements

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

The Java language has a wide variety of modifiers, including the following:

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Control Structures II. Repetition (Loops)

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

204111: Computer and Programming

Example: Monte Carlo Simulation 1

Transcription:

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

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 } CaseExpressions 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 Initialization Expression Test Expression True Statement or Block Update Expression False

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? o When 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)