Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Size: px
Start display at page:

Download "Repe$$on CSC 121 Fall 2015 Howard Rosenthal"

Transcription

1 Repe$$on CSC 121 Fall 2015 Howard Rosenthal

2 Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while for Learn nested looping Learn how to use break statements to exit a loop Begin to learn how to deal with situations where faulty or out of range input is supplied 2

3 Introduc$on to Loops Many of the tasks performed by computers require repetition, often massive repetition Using repetitive syntax can make your code more concise and easier to write and debug Java has three types of repetitive constructs (also known as loops): while; dowhile; or for Loops are built out of several fundamental statements because there are three things (in each of the three types of loops) that must be done correctly: The loop must be initialized correctly. The ending condition must be tested correctly. The body of the loop must change the condition that is tested. Overlooking one of these aspects results in a defective loop and a sometimes difficult to find program bug! Usually each of these three considerations is located in a different spot. No wonder that loops often go wrong! You have to plan out the logic of your program in order to effectively use loops and conditionals 3

4 Types of Loops type counting loop sentinel-controlled loop result-controlled loop description Uses a loop control variable to count upwards or downwards (usually by an integer increment.) Loop keeps going until a special value is encountered in the data. Loop keeps going until a test determines that the desired result has been achieved. 4

5 The while Statement Here is a program with a loop. It contains a while statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a while loop public class LoopExample public static void main (String[] args ) // start count out at one int count = 1; while ( count <= 3 ) System.out.println( "count is:" + count ); count = count + 1; // add one to count System.out.println( "Done with the loop" ); 5

6 The Basic Syntax of the while Statement while (condition) statement 1; statement 2; o 0 o statement n; You execute through the entire block repetitively until the condition is false unless you encounter a break statement The break will typically occur based on a separate condition tested with an if statement 6

7 Basic Terminology of the while Statement The condition is a Boolean expression: something that evaluates to true or false. The condition can be complicated, using many relational operators and logical operators. A single statement is allowed Without braces only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. If one of the statements in the while block doesn t eventually change the value of the condition then the loop goes on forever. The while loop may not be executed at all if the initial condition is false There is not a semi-colon after the while statement. If you put one there you will end the loop before it executes anything 7

8 Counters can be decremented rather than incremented Here is a program with a loop. It contains a while statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a while loop decrementing public class WhileLoopExample public static void main (String[] args ) int count = 2; // count is initialized while ( count >= 0 ) // count is tested System.out.println( "count is:" + count ); count = count - 1; // count is changed by -1 System.out.println( "Done counting down." ); 8

9 The do-while Statement Here is a program with a loop. It contains a do statement, followed by a block of code, followed by a while statement. // Example of a do-while loop public class DoWhileExample public static void main (String[] args ) int count = 1000; // initialize do System.out.println( count ); count++ ; // change s after the entire block is executed while ( count < 10 ); // test System.out.println( "Done with the loop" ); 9

10 The Basic Syntax of the do-while Statement do statement1; statement2; o 0 0 statementn; while (condition); 10

11 Basic Terminology of the do-while Statement The condition is a Boolean expression: something that evaluates to true or false. The condition can be complicated, using many relational operators and logical operators. A single statement is allowed Without braces to create a block only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. The do-while is always executed at least once, if the do statement is executed There is a semi-colon after the while statement in a dowhile 11

12 The for Statement Here is a program with a loop. It contains a for statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a for loop public class ForExample public static void main (String[] args ) int sum=0; for ( int count = 0; count <= 5; count++ ) sum = sum + count ; System.out.print( count + " " ); System.out.println( \nsum is: " + sum ); Initialization count = 0 loop condition count <= 5 sum = sum + count Print count count++ Print sum false 12

13 The Basic Syntax of the for Statement for (initialization; loop condition; update statements) statement1; statement2; o 0 0 statementn; 13

14 Basic Terminology of the for Statement initialization Used to initialize basic variables used in the loop condition More than one variable can be set, separated by commas You can declare the variable in the for statement, but then it is only valid within the for loop that it is created for for (int j=3, k=4; ; ) If no variables are set, you must have a ; before the loop condition this typically means that the variable has been set prior to the for statement The initialization portion of the for statement is only executed once, each time you enter the loop loop condition A boolean expression evaluates as true or false Evaluated at the beginning of each loop Although this statement can be left out, leaving it out could lead to an infinite do loop, unless you execute a break statement inside the loop 14

15 Basic Terminology of the for Statement (2) update statement(s) Increases or decreases a value, typically one or more used in the loop condition Should always executed at the end of the loop body that s why we use postfix Can include more than one statement, separated by commas for( ; ; i++, j= j+5) Notes: If you are eliminating multiple parts of a for statement it may be better to use a while or do-while Don t stuff too many extraneous things into the for statement, you ll confuse yourself 15

16 Nested Loops A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too. Inner loops always stay completely inside their outer loops An inner loop may be skipped over during the execution of an outer loop For instance, if the loop is inside of an if block that isn t executed, then that loop wouldn t be executed 16

17 Nested Loop Example // Example of nested loop public class NestedLoops public static void main (String[] args ) int height =5; int width = 4; for ( int i = 0 ; i < height ; i++ ) for ( int j = 0 ; j< width ; j++ ) System.out.print( "*" ) ; System.out.println( "" ) ; Now let s look at the MultTable Example 17

18 The break statement Used to exit the innermost loop that the break is found within, unless the loop is labeled Loop is labeled with looplabelname: followed by the loop Next statement executed is the first statement beyond the scope of that loop If you label a loop the break statement can be used to exit through an outer nesting We ll look at BreakLabeledLoop.java 18

19 The flag or sendnel A flag or sentinel is a value appended to a data collection that signals the end of the data. The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to control when the loop is done. In following code fragment, the user enters a zero when the sum is complete. Zero is the sentinel. Here is how the program should work import java.util.scanner; // Add up integers entered by the user. // After the last integer, the user enters a 0. class AddUpNumbers public static void main (String[] args ) Scanner keyboard = new Scanner( System.in ); int value, sum = 0; System.out.print( "Enter first integer (enter 0 to quit): " ); value = keyboard.nextint(); //we initialize value before entering the loop while ( value!= 0 ) sum = sum + value; System.out.print( "Enter next integer (enter 0 to quit): " ); value = keyboard.nextint(); //update value inside the loop System.out.println( "Sum of the integers: " + sum ); 19

20 Bad Input data There are cases when erroneous data is entered There are many options Request revised data Exit the program In order to do either you must check the data first Note: Some inputs will cause the program to crash Can you name 0ne? We will look at GeneralAverage in a few minutes 20

21 Scope of a Variable (1) A variable s scope is determined by the highest level of braces within which it is defined. It works at that level and all nested level If you use the same variable name in an outer and nested blocks, an error will occur. If you exit a block where a variable is defined you can reuse the variable name It s values are separate from the originally named variable Don t use the same variable name twice in a program it only confuses things. You are allowed to continuously redeclare a variable in the same statement with a loop Scope is extremely important to understand in nested loops. Once you leave the loop a variable declared in the loop no longer exists. 21

22 Scope of a Variable (2) / Demonstrate block scope. class Scope public static void main(string args[]) int n1; // Visible in main n1 = 10; if(n1 == 10) // start new scope int n2 = 20; // visible only to this block // n1 and n2 both visible here. System.out.println("n1 and n2 : "+ n1 +""+ n2); // n2 = 100; // Error! n2 not known here // n1 is still visible here. System.out.println("n1 is " + n1); 22

23 Scope of a Variable (3) class LifeTime public static void main(string args[]) int i; for(i = 0; i < 3; i++) int y = -1; System.out.println("y is : " + y); Variable y is declared inside for loop block. Each time when control goes inside For loop Block, Variable is declared and used in loop. When control goes out of the for loop then the variable becomes inaccessible. 23

24 Scope of a Variable (4) class ScopeInvalid public static void main(string args[]) int num = 1; // creates a new scope int num = 2; // Compile-time error // num already defined class ScopeValid public static void main(string args[]) // creates a new scope int num = 1; // creates a new scope int num = 2; 24

25 Programming Exercises Class (1) Exercise 2 Pictures Write a program that reads an integer n and prints the following right triangle with base and height n 1 x 2 xx 3 xxx 4.. n xxxxxx.x 25

26 Programming Exercises Class(2) Exercise 9 GeneralAverage Write a program that calculates the average of n test scores, such that each score is an integer in the range 0 to 100. Your program should first prompt for an integer n and then request n scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 26

27 Programming Exercises Lab (1) Exercise 3 MorePictures Write a program that accepts an integer n and prints out the following picture of a diamond with 2n-1 rows 1 X 2 X X X 3 X X X X X n XXXXXXXXXXX (2n-1 times). 2n-1 X 27

28 Programming Exercises Lab (2) Exercise 10 Modified Average Write a program that accepts a list of n test scores, and then finds the average of the n-1 highest scores on the list that is, the lowest score on the list is not included in the average. For example, if the test scores are 90, 80, 70, and 60, the average is computed as ( )/3. The low score of 60 is excluded Your program should first prompt for an integer n and then request n scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 28

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal Control Statements Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review some of Java s control structures Review how to control the flow of a program via selection mechanisms Understand if, if-else,

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Chapter 4: Control structures. Repetition

Chapter 4: Control structures. Repetition Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

Repetition and Loop Statements Chapter 5

Repetition and Loop Statements Chapter 5 Repetition and Loop Statements Chapter 5 1 Chapter Objectives To understand why repetition is an important control structure in programming To learn about loop control variables and the three steps needed

More information

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Chapter 4: Control structures

Chapter 4: Control structures Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

Introduction to the Java Basics: Control Flow Statements

Introduction to the Java Basics: Control Flow Statements Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

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

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Unit 2, Part 2 Definite Loops Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Let's say that we're using a variable i to count the number of times that

More information

Repetition, Looping CS101

Repetition, Looping CS101 Repetition, Looping CS101 Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x ); Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program

More information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

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

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

More information

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

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

Top-Down Program Development

Top-Down Program Development Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable

More information

Recap: Assignment as an Operator CS 112 Introduction to Programming

Recap: Assignment as an Operator CS 112 Introduction to Programming Recap: Assignment as an Operator CS 112 Introduction to Programming q You can consider assignment as an operator, with a (Spring 2012) lower precedence than the arithmetic operators First the expression

More information

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming I - Unit 5 Lecture page 1 of 14 page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements

More information

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. Looping. ++ is the increment operator. Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #7: Variable Scope, Constants, and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112

More information

Flow of Control: Loops. Chapter 4

Flow of Control: Loops. Chapter 4 Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

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

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

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

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

More information

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - Loops Stephen Scott (Adapted from Christopher M. Bourke) 1 / 1 Fall 2009 cbourke@cse.unl.edu Chapter 5 5.1 Repetition in

More information

Iteration statements - Loops

Iteration statements - Loops Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or

More information

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type)

More information

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

204111: Computer and Programming

204111: Computer and Programming 204111: Computer and Programming Week 4: Control Structures t Monchai Sopitkamon, Ph.D. Overview Types of control structures Using selection structure Using repetition structure Types of control ol structures

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Looping. Arizona State University 1

Looping. Arizona State University 1 Looping CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 5 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

! 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

! 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 Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

Repetition with for loops

Repetition with for loops Repetition with for loops So far, when we wanted to perform a task multiple times, we have written redundant code: System.out.println( Building Java Programs ); // print 5 blank lines System.out.println(

More information

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18 Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

More information

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A. Chapter 5 While For 1 / 54 Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - s Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 While For 2 / 54 5.1 Repetition

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 02 / 15 / 2016 Instructor: Michael Eckmann Questions? Comments? Loops to repeat code while loops for loops do while loops Today s Topics Logical operators Example

More information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

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

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1 Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)

More information

Chapter Goals. Contents LOOPS

Chapter Goals. Contents LOOPS CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

More information

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

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming 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:

More information

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4) Loops! Flow of Control: Loops (Savitch, Chapter 4) TOPICS while Loops do while Loops for Loops break Statement continue Statement CS 160, Fall Semester 2014 2 An Example while Loop Step- by- step int count

More information

CS1150 Principles of Computer Science Loops (Part II)

CS1150 Principles of Computer Science Loops (Part II) CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?

More information

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

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths. Loop Control There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first,

More information

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

More information

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

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops. Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8 Handout 5 Loops. Loops implement repetitive computation, a k a iteration. Java loop statements: while do-while for 1. Start with the while-loop.

More information

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

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

More information

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation Program Development Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr The creation of software involves four basic activities: establishing

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

More information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014 Lesson 6A Loops By John B. Owen All rights reserved 2011, revised 2014 Topic List Objectives Loop structure 4 parts Three loop styles Example of a while loop Example of a do while loop Comparison while

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

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

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

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

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

More information

Principles of Computer Science I

Principles of Computer Science I Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG 1 Notice Prepare the Weekly Quiz The weekly quiz is for the knowledge we learned in the previous week (both the

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

3chapter C ONTROL S TATEMENTS. Objectives

3chapter C ONTROL S TATEMENTS. Objectives 3chapter C ONTROL S TATEMENTS Objectives To understand the flow of control in selection and loop statements ( 3.2 3.7). To use Boolean expressions to control selection statements and loop statements (

More information

CS121: Computer Programming I

CS121: Computer Programming I CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours

More information

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours

More information

Chapter 17. Iteration The while Statement

Chapter 17. Iteration The while Statement 203 Chapter 17 Iteration Iteration repeats the execution of a sequence of code. Iteration is useful for solving many programming problems. Interation and conditional execution form the basis for algorithm

More information

The for Loop. Lesson 11

The for Loop. Lesson 11 The for Loop Lesson 11 Have you ever played Tetris? You know that the game never truly ends. Blocks continue to fall one at a time, increasing in speed as you go up in levels, until the game breaks from

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

Bjarne Stroustrup. creator of C++

Bjarne Stroustrup. creator of C++ We Continue GEEN163 I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. Bjarne Stroustrup creator

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Computer Science is...

Computer Science is... Computer Science is... Automated Software Verification Using mathematical logic, computer scientists try to design tools to automatically detect runtime and logical errors in huge, complex programs. Right:

More information

Loops and Files. of do-while loop

Loops and Files. of do-while loop L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while Pull Lecture Materials and Open PollEv Poll Everywhere: pollev.com/comp110 Lecture 12 else-if and while loops Once in a while Fall 2016 if-then-else Statements General form of an if-then-else statement:

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

CS112 Lecture: Loops

CS112 Lecture: Loops CS112 Lecture: Loops Objectives: Last revised 3/11/08 1. To introduce some while loop patterns 2. To introduce and motivate the java do.. while loop 3. To review the general form of the java for loop.

More information

AP Programming - Chapter 6 Lecture

AP Programming - Chapter 6 Lecture page 1 of 21 The while Statement, Types of Loops, Looping Subtasks, Nested Loops I. The while Statement Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly.

More information

Warmup : Name that tune!

Warmup : Name that tune! Warmup : Name that tune! Write, using a loop, Java code to print the lyrics to the song 99 Bottles of Beer on the Wall 99 bottles of beer on the wall. 99 bottles of beer. Take one down, pass it around,

More information

Loops. GEEN163 Introduction to Computer Programming

Loops. GEEN163 Introduction to Computer Programming Loops GEEN163 Introduction to Computer Programming Simplicity is prerequisite for reliability. Edsger W. Dijkstra Programming Assignment A new programming assignment has been posted on Blackboard for this

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

Module 4: Decision-making and forming loops

Module 4: Decision-making and forming loops 1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The

More information

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1 COMP 202 Programming With Iterations CONTENT: The WHILE, DO and FOR Statements COMP 202 - Loops 1 Repetition Statements Repetition statements or iteration allow us to execute a statement multiple times

More information

Iterative Languages. Scoping

Iterative Languages. Scoping Iterative Languages Scoping Sample Languages C: static-scoping Perl: static and dynamic-scoping (use to be only dynamic scoping) Both gcc (to run C programs), and perl (to run Perl programs) are installed

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

More information

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/else

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information