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

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
CS107 Introduction to Computer Science Loops. Instructions Pseudocode Assign values to variables using basic arithmetic operations x = 3 y = x/10 z =
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
UCT Department of Computer Science Computer Science 1015F Iteration
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Repetition-Counter control Loop
CiS 260: App Dev I Chapter 4: Control Structures II.
Repetition-Sentinel,Flag Loop/Do_While
Chapter 2.2 Control Structures (Iteration)
( Iteration / Repetition / Looping )
Lecture 07 More Repetition Richard Gesick.
Chapter 5: Control Structures II
Lecture 4B More Repetition Richard Gesick
Control Structure Senior Lecturer
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Java Programming Loops
Control Statements Loops.
Repetition Control Structure
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Control Statements Loops.
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.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

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

Loops Loop statements implement repetition. There are 3 types of loops in Java: – while loops The programmer specifies all the components that control the loop. – for loops Iterate over a collection Generate specific sequences of numbers. – do…while loops - NOT COVERED (and not needed) break & continue Types of problems 2

Motivation Suppose 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.

Towards writing the password program 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 4

while loop Syntax: while (boolean_expression){ line 1 line 2 … line n } first line after while Notice the similarity in syntax with the if statement. 5 body of the while loop. header of the while loop.

while loop execution while (boolean_expression){ line 1 line 2 … line n } first line after loop Loop execution: – Step 1: evaluate boolean_expression. – 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). 6

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."); 7

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 int i = 0; while (i <= N){ System.out.printf("i = %d\n", i); i = i + 1; } System.out.println("Done with the while loop."); 8 iN

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; while (i <= N){ System.out.printf("i = %d\n", i); i = i + 1; } System.out.println("Done with the while loop."); 9 Variable i is called a counter. Initialize the counter. Update the counter. Condition involving the counter.

Designing a 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.Update variables within the body of the loop, as needed. 3.Test border cases in the condition do this after step 2. 10

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 … } … } … 11

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

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; } 13

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; … } … } 14

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

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); } 16

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 – N, N-1,… 3,2,1 Even numbers: – Generate and print even numbers – 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 Strings: – Print string letters – Print string letters with a certain property 17

Compute 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: … + N – N!: 1 * 2 * 3 * 4 *... * N – sum of even and product of odd numbers. 18

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 19

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

Problem type 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. 21

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"); 22

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

The for loop 24

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

Example: for loop over a string What will this code do? 26 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("---"); }

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. 27