Loops (while and for)

Similar documents
Repetition Structures

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

REPETITION CONTROL STRUCTURE LOGO

Loops / Repetition Statements

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Loops / Repetition Statements

COMP 111. Introduction to Computer Science and Object-Oriented Programming

Chapter 4: Control structures. Repetition

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

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

Chapter 4: Control structures

Lecture 7 Tao Wang 1

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Repetition and Loop Statements Chapter 5

Chapter Goals. Contents LOOPS

Why Is Repetition Needed?

Chapter 5: Control Structures II (Repetition)

Chapter 4 Introduction to Control Statements

Computer Programming I - Unit 5 Lecture page 1 of 14

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

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

CS110D: PROGRAMMING LANGUAGE I

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

STUDENT LESSON A12 Iterations

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

Introduction. C provides two styles of flow control:

Increment and the While. Class 15

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

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

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Repetition, Looping. While Loop

Condition Controlled Loops. Introduction to Programming - Python

MODULE 2: Branching and Looping

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

Control Structures II. Repetition (Loops)

Information Science 1

Loops. CSE 114, Computer Science 1 Stony Brook University

Repetition, Looping CS101

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

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

Score score < score < score < 65 Score < 50

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

LOOPS. Repetition using the while statement

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

Iteration statements - Loops

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Java Coding 3. Over & over again!

Quiz Determine the output of the following program:

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

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Condition Controlled Loops. Introduction to Programming - Python

Chapter 5: Loops and Files

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

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Dept. of CSE, IIT KGP

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

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

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

3 The L oop Control Structure

Information Science 1

Computers Programming Course 7. Iulian Năstac

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

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

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Chapter 3. More Flow of Control

To become familiar with array manipulation, searching, and sorting.

(Refer Slide Time: 00:26)

CompSci 125 Lecture 09. Chapter 5: while, break and continue statements Iterators and the ArrayList Class

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Subject: PIC Chapter 2.

Branching is deciding what actions to take and Looping is deciding how many times to take a certain action.

C Programming for Engineers Structured Program

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Course Outline. Introduction to java

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

CS1100 Introduction to Programming

Control Statements. Musa M. Ameen Computer Engineering Dept.

Example: Monte Carlo Simulation 1

ECE 122. Engineering Problem Solving with Java

Flow Control. CSC215 Lecture

Chapter 5: Control Structures

8. Control statements

Lecture Transcript While and Do While Statements in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

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

Flow of Control: Loops. Chapter 4

Transcription:

Loops (while and for) CSE 1310 Introduction to Computers and Programming Alexandra Stefan 1

Motivation Was there any program we did (class or hw) where you wanted to repeat an action? 2

Motivation Name banner: user enters name and repeats. Program prints. E.g. for Mavs and 3, it will print: Go Mavs! Go Mavs! Go Mavs! ** Check if all characters in a string (given as name) are English letters. Variation: count how many are English letters or spaces. String printing: Reverse to simulate a mirroring effect. Stacking effect (vertical print) in Microsoft Word. One letter per line Problem solving: decouple components: index generation ** Repeat animation for a certain number of times, without hardcoding 3 times (like in hw we hardcoded 3 circles). Guess a number or recognize a password. M o t i v a t i o n Computer player in a guessing game: the computer will have to guess. Print a weekly/monthly schedule (or To Do list). May give what day of week the 1 st of the month is to show day names (e.g. Feb 1 st 2018 was a Thursday) M o t i v a t i o n 3

Loops 2 kinds of repetition: until something happens or For a specific number of times (known when the repetition starts) Loop statements implement repetition. There are 3 types of loops in Java: while loops Good for cases when waiting for an event to happen. E.g. Enter numbers until value 0 is entered convenient for getting user input for arrays. Ask for the password until a matching one was entered. NOTE: it will not stop as soon as the even happened, but when the condition is checked. for loops Good when we need to repeat a set of actions a certain number of times. E.g.: Examine every character in a string (to print, or see if English letter or to count vowels) Print the first 10 prime numbers. Compute homework average grade for each student (in a collection). Can be set-up to behave as while loops as well: stop when an event happens. do while loops - NOT COVERED (and not needed) break & continue - covered, but not recommended. Types of problems 4

Practice: basic iteration Algorithm and problem solving Loop control: infinite loop and loop that never executes Create a program that iterates as long as the user wants to continue (asked after each iteration) 10 times N times (N entered by the user) Generate numbers 1,2,., N (e.g. model a machine giving line tickets like at the DMV office) N, N-1, 3,2,1 (e.g. model a count-down) Even numbers: Generate and print even numbers (e.g. part of a math application for kids) Generate all numbers, but print only the even ones Generate all numbers, take different action based on a property Draw the flow of control diagram. Be aware of the sequence of numbers generated by each branch. Print N stars Name banner (adjusts to name length, vertical or horizontal orientation). Strings: Print string letters Print string letters with a certain property Check that all symbols are English letters. 5

Problem type: Cumulative operations Algorithm, typical setup (counter, accumulator) Separate the process of generating the values from the process of computing the cumulative operation. Practice: compute the following values: Sum: 1 + 2 + + N N!: 1 * 2 * 3 * 4 *... * N sum of even and product of odd numbers. 6

Deeper understanding Do you see what the general problem corresponding to each of the specific examples above? What general problems have we seen? 7

Problem type: property in a collection Check if a collection (of values/objects) has a certain property. Example: The user enters x and y, with x < y. Print True if any (at least one) number in that range (including x and y) is divisible by 13. Print False otherwise (note: this is the difficult part!). Extra: if x > y, swap their values. 8

More practice: combine problems Keep asking for user input (an integer) until the number they enter would be a leap year. 9

The for loop 10

for loop The for loop has the loop control instructions at the top. Syntax: for (init; condition; update){ line 1 line 2 line n } body or suite of the for loop header 11

Example: for loop over a string Draw flowchart Variable i is called a counter. Initialize the counter. int i; Condition involving the counter. String s = "Hello there!"; for(i=0; i<s.length(); i=i+1){ char c = s.charat(i); Update the counter. System.out.printf("i=%d, letter: %c\n", i, c); System.out.println("---"); } 12

Example: for loop over a string What will this code do? Trace the value of the variables throughout the program execution. i c int i; String s = "Hello there!"; for(i=0; i<s.length(); i=i+1){ char c = s.charat(i); System.out.printf("i=%d, letter: %c%n", i, c); System.out.println("---"); } 13

Loop - variations Loop mechanism: as long as condition is true, repeat body of the loop. Examples with counter: Counter goes up in increments: +1, +5, *2 Is +variable allowed? E.g. for(j=0; j<n;j=j+x) Counter goes down: -1, -3, /4 Example without counter: E.g. Until user enters specific number or string, until certain random number is produced, Variations in syntax : Missing init Missing update Condition can also be missing, but we are NOT DOING THAT. Issues/bugs Infinite loop not marking the body of the loop, Semicolon after header: for(.); Same issue as with: if ( ); 14

Example 2: for loop with a string 1. Print string characters in reversed order. 2. Count the number of vowels in text entered by the user. 3. Check is all characters in a string are English letters. 4. Print banners (with any name, not just the one from the example) ************* * alex stef * ************* ************* * alex stef * ************* ***** * a * * l * * e * * x * * * * s * * t * * e * * f * ***** ***** * a * * l * * e * * x * * * * s * * t * * e * * f * ***** 15

Towards writing a password program We want to write a program that does this: Has a hardcoded string representing a saved password. Asks the user to enter their password until there is a match. First, let s solve the simpler version: get only one string from the user (they have only one chance to enter their password) Pseudocode Flowchart Code Next: solve the original problem 16

while loop 17

while loop execution while (boolean_expression){ line 1 line 2 line n } first line after loop body of the while loop. Loop execution: Step 1: evaluate boolean_expression. header of the while loop. Step 2: If boolean_expression is false, go to the first line after the loop. Step 3: If boolean_expression is true, execute the body of the while loop, and go back to step 1 (evaluate the boolean expression). 18

while loop with sentinel Example: keep asking for user input until they enter 0. int N = 1; while (N!= 0){ System.out.printf("Enter an integer: "); N = in.nextint(); } System.out.println("Done with the while loop."); 19

while loop with counter What does this code do? Trace the execution on paper (fill in table on the right). Use the debugger check your answers from above. System.out.println("Enter N: "); int N = in.nextint(); // assume user enter 5 i N int i = 0; while (i <= N){ System.out.printf("i = %d\n", i); i = i + 1; } System.out.println("Done with the while loop."); 20

while loop with counter What does this code do? Trace the execution on paper. Use the debugger check your answers from above. System.out.println("Enter N: "); int N = in.nextint(); int i = 0; Variable i is called a counter. Initialize the counter. while (i <= N){ Condition involving the counter. System.out.printf("i = %d\n", i); i = i + 1; Update the counter. } System.out.println("Done with the while loop."); 21

Designing a for/while loop The loop must terminate exactly when needed (not too early or too late). 1. Define a test (boolean expression), that determines when to stay in the loop and when to exit. 2. Initialize and update variables that control the loop, as needed. 3. Test border cases in the condition do this after step 2. 22

Nested loops One loop in the body of another loop /* What does the following program print? How many times does each line execute? */ int i = 1; while (i < 4){ // outer loop System.out.printf("i =%d\n", i); int k = 1; while (k < 6){ // inner loop System.out.printf(" i = %d, k = %d\n", i, k); k = k + 1; } i = i + 1; } System.out.printf("Bye"); 23

Last instruction before loop False cond True False... cond True 1 st instruction after loop 24

Extra 25

More on Loops: break and continue Loop behavior discussed so far last instruction before loop False True cond New: 2 special jumps At the beginning After the loop...... 1 st instruction after loop 26

Normal loop last instruction before loop Loop with break or continue last instruction before loop False cond True False cond True............ continue break 1 st instruction after loop 1 st instruction after loop 27

Loop with break last instruction before loop False cond True.... The break instruction must be in a branch of an if-statement. Otherwise there is NO loop: it will break after the first iteration.... break break 1 st instruction after loop 28

Loop with continue last instruction before loop False cond True continue The continue instruction must be in a branch of an if-statement. Otherwise there is NO loop: it will break after the first iteration... continue... 1 st instruction after loop 29

continue last instruction before loop last instruction before loop False cond True False cond True...... continue...... 1 st instruction after loop 1 st instruction after loop 30

The break statement break forces termination of the current loop. Syntax: while (condition){ if (condition){ } } break # after this line it moves to the next instruction after while 31

The break statement Split opinions on the usage of break Example: print the first number >= N that is divisible by 13. 32

The break statement Example: print the first number >= N that is divisible by 13. System.out.println("Enter N: "); int N = in.nextint(); int i = N; while (true){ } if (i % 13 == 0){ System.out.print("first i>=%d,divisible by 13 is:%d", N,i); break; //after this line it moves to the next instr after while } i = i+1; 33

The continue statement continue skips the rest of the body of the loop and goes back to the header of the loop (which will cause it to execute the next iteration, or to terminate). Syntax: while (condition){ if (condition){ } continue; } 34

The continue statement Example: print numbers between 1 and N that are divisible by 13. 35

The continue statement Example: print numbers between 1 and N that are divisible by 13. System.out.println("Enter N: "); int N = in.nextint(); int i = 0; while (i < N){ i = i+1; if (i % 13!= 0){ //not divisible by 13, continue; } System.out.println("%d is divisible by 13", i); } 36

Practice: break and continue Pb1: Repeat a certain operation until the user enters a specific value: As long as user enters values greater or equal to 0: show letter grade based on score If strictly negative: finish Pb2: Same letter grade problem, but stop only when user enters -1. Skip scores out of range (maybe print a message), print letter grade for scores in range. Variation: in addition to printing the letter grade, also concatenate it into a string 37