Lesson 6A – Loops By John B. Owen All rights reserved ©2011.

Slides:



Advertisements
Similar presentations
COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Advertisements

Iteration While / until/ for loop. Iteration: while/ Do-while loops Iteration continues until condition is false: 3 important points to remember: 1.Initalise.
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 6, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
COMP102 – Programming Fundamentals I LA2B (Mon 5-7pm) LA2E (Fri 3-5pm) LA2F (Fri 5-7pm) TA: Jackie Lo.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
1 Fall 2008ACS-1903 Ch 4 Loops and Files while loop do-while loop Other topics later on …
1 Fall 2007ACS-1903 Ch 4 Loops and Files Increment & decrement statements while loop do-while loop Other topics later on …
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 4: Control Structures II
Unit 5 – “Watch Out!”. Introduction New Topics Case Structures New Functions Less? Comparison Function Ultrasonic Sensor.
Lesson 6C – Loops 3 – Advanced File Processing By John B. Owen All rights reserved ©2011.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Lesson 1.7 Dividing Integers Standards: NS 1.2 and AF 2.1 Objectives: Dividing Integers Evaluate variable expressions.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
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.
CS101 Computer Programming I Chapter 4 Extra Examples.
Chapter 4: Elementary Number Theory and Methods of Proof 4.8 Application: Algorithms 1 Begin at the beginning…and go on till you come to the end: then.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Fundamental Programming Fundamental Programming More on Repetition.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
COMP Loop Statements Yi Hong May 21, 2015.
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
While ( number
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Follow up from lab See Magic8Ball.java Issues that you ran into.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
7 - Programming 7J, K, L, M, N, O – Handling Data.
FOP: While Loops.
Trace Tables In today’s lesson we will look at:
While Loops in Python.
Do it now activity Green pen activity in books.
Iterations Programming Condition Controlled Loops (WHILE Loop)
Control Structures - Repetition
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Iteration with While You can say that again.
Computers & Programming Languages
Lesson 05: Iterations Topic: Introduction to Programming, Zybook Ch 4, P4E Ch 5. Slides on website.
Lecture Notes – Week 3 Lecture-2
Counting Loops.
Nate Brunelle Today: Repetition, Repetition
Coding Concepts (Basics)
LOOPS BY: LAUREN & ROMEO.
Seating “chart” Front - Screen rows Back DOOR.
Introduction to Computer Science
Decisions, decisions, decisions
Repetition Statements (Loops) - 2
Java LESSON 3 Loops.
While Loops in Python.
Chapter 3 Flow of Control Loops in Java.
Presentation transcript:

Lesson 6A – Loops By John B. Owen All rights reserved ©2011

Objectives Loop structure – 4 parts Three loop styles Example of a while loop Example of a do while loop Comparison – while vs do while Example of a for loop Three loops…compare and contrast Lesson Summary / Labs Acknowledgement of use Topic List Lesson 6A - Loops2

In this lesson you will learn about using a loop. This technique is very powerful and useful in many ways. Sometimes it is called iteration, another name for looping. Objectives Lesson 6A - Loops3

A loop is a powerful control structure in programming that allows a task to be repeated several times, such as outputting a row of 20 stars, or counting from 1 to 20, or inputting from the keyboard 5 numbers...the possibilities are many. Loop structure Lesson 6A - Loops4

Every loop has four basic parts that MUST be present in order for the loop to work properly. START CHECK STEP ACTION Four parts of a loop Lesson 6A - Loops5

This is where the loop begins its process, usually managed by a loop control variable, most often an integer that begins at zero. int x = 0; is a very common start to a loop The START Lesson 6A - Loops6

This is a boolean expression which, while its condition is TRUE, allows the loop action to continue, but stops the loop when the condition becomes FALSE. An example of a check expression would be x<10. The CHECK Lesson 6A - Loops7

If the current value of x is less than 10, the loop continues. When the value of x becomes equal to or greater than 10, the loop will stop. The CHECK Lesson 6A - Loops8

This is most often a mathematical process of adding to or subtracting from a loop control variable, which eventually (hopefully) will reach a value that will cause the CHECK condition to be FALSE. The STEP Lesson 6A - Loops9

x=x+1 is a very common step which increases the value of x by 1… x+=1 is a shortcut for this… as is x++ The STEP Lesson 6A - Loops10

This is the task to be repeated inside the loop, and can be any number of things, for example: Output or calculate something Read data from the keyboard or a file, or write data to a file Animation control The ACTION Lesson 6A - Loops11

In Java there are three styles of loops: for while do while All three work in similar ways, but have slight differences. Three styles of loops Lesson 6A - Loops12

Quite likely the most commonly used structure is the for loop, but the while and do while loop structures are sometimes better suited for use in some cases. Three styles of loops Lesson 6A - Loops13

The while loop Lesson 6A - Loops14 Here is an example of a while loop that will output the word HELLO five times, along with the current value of x, the loop control variable:

The while loop Lesson 6A - Loops15 Notice that the loop control variable x, is given a starting value of 1. When the condition of the boolean expression (x<=5) is first checked, it is TRUE, because x currently is storing the value 1, which is indeed less than or equal to 5.

The while loop Lesson 6A - Loops16 Since the boolean condition is TRUE, the inside block of the loop is executed, containing the ACTION and the STEP. " HELLO 1 " is output, then x's value is increased by 1, becoming 2.

The while loop Lesson 6A - Loops17 When the closing brace is reached, the compiler goes back to the "while" and re-checks the condition. Since x contains the value 2, the condition is still TRUE, and the ACTION and STEP execute again.

The while loop Lesson 6A - Loops18 This repetitive cycle continues until x contains the value 6, which causes (x<=5) to be FALSE, thus stopping the loop process. The program control then falls through to the next command following the loop.

The while loop Lesson 6A - Loops19 If you trace the values of x, they start at 1, then become 2, 3, 4, 5, and finally 6. When the values were 1 through 5, the CHECK condition was true, and the ACTION and STEP inside the loop were executed, causing five outputs. Sometimes it helps to do a T-chart to see how the loop works, like this one: x |x<=5 |action 1 | true | HELLO 1 2 | true | HELLO 2 3 | true | HELLO 3 4 | true | HELLO 4 5 | true | HELLO 5 6 | false | loop ends

The do while loop Lesson 6A - Loops20 Here is an example of a do while loop that does exactly the same thing as the while loop we just did. The do while loop performs the same task, but in a slightly different way. Can you tell the difference?

The do while loop Lesson 6A - Loops21 The first noticeable change is the word do at the beginning of the structure. The next major difference is that the CHECK happens at the end of the structure, AFTER the action and the step have occurred. Finally, the while statement finishes with a semi-colon, where in the first example there was NO semi-colon.

The do while loop Lesson 6A - Loops22 The most significant difference between the while and the do while loop is that the do while loop will ALWAYS executes at least once since the CHECK happens at the end.

while vs do while – a comparison Lesson 6A - Loops23 To demonstrate the difference between the while and the do while loop, each of the two previous program examples have been altered, with the value of x starting at 6. Check out the output!

while vs do while – a comparison Lesson 6A - Loops24 Notice carefully that the while loop never executes since the first CHECK is false because x has an intial value of 6. However, the do while executes once with the x value of 6 since the CHECK does not happen until the end of the structure.

The for loop Lesson 6A - Loops25 The for loop is clearly the most elegant of the three loop structures, in that it handles three of the four parts of the loop all in one compound statement, as you can see in the example below. It follows the same general pattern as the while loop: Start, then check, action if true, then step

The for loop Lesson 6A - Loops26 It continues the three part circular pattern of check, action, step until the check is FALSE, at which time the loop stops and program control falls through to the next statement.

The for loop Lesson 6A - Loops27 Notice very carefully that THERE IS NO SEMICOLON at the end of the for statement Putting a semi-colon here is a common error among beginners…dont do it!!!

The for loop – internal LCV Lesson 6A - Loops28 Another way to structure the for loop is to initialize the loop control variable inside the for statement, as shown below.

The for loop – internal LCV Lesson 6A - Loops29 There is one subtle difference in the output. Can you see it?

The for loop – internal LCV Lesson 6A - Loops30 The value of x is omitted from the Loop is finished… statement!!

The for loop – internal LCV Lesson 6A - Loops31 Since the loop control variable x is internal (was declared inside the loop structure), it only EXISTS inside the loop structure, therefore is not available for any statements outside the loop.

Clearly all three loops accomplish the main goal – the iteration or repetition of program statements. They just do it in slightly different ways. Some key differences among the three loops are: It is possible for the "while" loop and the "for" loop NEVER to execute. This happens when the FIRST CHECK of the boolean expression evaluates to FALSE. These are called PRETEST loops. Three loops…compare and contrast Lesson 6A - Loops32

On the other hand, the "do while" loop ALWAYS executes at least once since the FIRST CHECK happens only after the action of the loop is executed. It is called a POSTTEST loop. Another difference between the loops is that both the "while" and "do while" loops require more than one statement in the body of the loop (ACTION and STEP), which means they must be included in a "block"...between the "{" and "}". Three loops…compare and contrast Lesson 6A - Loops33

Since the for loop encompasses the START, CHECK, and STEP inside the loop structure, and often only has one statement in the ACTION step, it does not need the braces for just one statement. However, the for loop CAN have multiple action statements, thus requiring the use of block brackets. Three loops…compare and contrast Lesson 6A - Loops34

In this lesson, you learned about the three basic loop structures: while, do while, and for. You learned how each has four parts, arranged in different ways. Now it is time to practice several examples. Lesson Summary Lesson 6A - Loops35

All the labs for this lesson will be created in a class called MyLoops. Create a folder to contain all of these labs, and then create a class called MyLoops to contain all of the static methods you will create. Labs Lesson 6A - Loops36

The difference between these methods and the ones you did in the last lesson is that these will be void methods, not return methods. Void methods simply DO something inside the method, instead of returning an answer. Some examples will be shown to help you get started. Labs Lesson 6A - Loops37

Method 1 – row5Stars Lesson 6A - Loops38 WAM that will output five stars in a row using a while loop. There is no input for this method…just simple output. Notice the way the method is called…this is how you call a void method…simply state its name.

Method 2 – row5Stars2 Lesson 6A - Loops39 WAM that will output five stars in a row using a do while loop. Copy and paste the row5Stars() method and make the adjustments needed to make it a do while loop.

Method 3 – row5Stars3 Lesson 6A - Loops40 WAM that will output five stars in a row using a for loop. Again, copy and paste and make the adjustments.

Method 4 – rowNStars Lesson 6A - Loops41 WAM that will receive an integer parameter N and output N stars in a row using a while loop. Use a while loop in the main method to input values from a data file. A portion of the solution is shown.

Method 5 – rowNStars2 Lesson 6A - Loops42 WAM that will receive an integer parameter N and output N stars in a row using a do while loop.

Method 6 – rowNStars3 Lesson 6A - Loops43 WAM that will receive an integer parameter N and output N stars in a row using a for loop.

Method 7 – colNStars Lesson 6A - Loops44 WAM that will receive an integer parameter N and output N stars in a COLUMN using a while loop.

Method 8 – colNValues Lesson 6A - Loops45 WAM that will receive an integer parameter N and output the VALUES FROM 1 TO N in a COLUMN using a do while loop.

Method 9 – MtoNValues Lesson 6A - Loops46 WAM that will receive two integer parameters M and N and output the VALUES FROM M TO N in a ROW using a for loop. There should be exactly one space after each value.

Method 10 – MtoNEvens Lesson 6A - Loops47 WAM that will receive two integer parameters M and N and output the EVEN VALUES FROM M TO N in a ROW using a while loop. There should be exactly one space after each value. Hint: use an if statement with the mod (%) operation.

Method 11 – MtoNOdds Lesson 6A - Loops48 WAM that will receive two integer parameters M and N and output the ODD VALUES FROM M TO N in a ROW using a do while loop. There should be exactly one space after each value.

Method 12 – diagonalNStars Lesson 6A - Loops49 WAM that will receive an integer parameter N and output a diagonal of stars using a for loop. Use the special printf technique you learned in Lesson 1D where the field width specifier helps to create a custom indent. The complete solution is shown. An explanation is provided on the next slide

Method 12 – diagonalNStars Lesson 6A - Loops50 Study carefully the indenting technique highlighted below. The format string is a concatenation of the %s format specifier using the changing value of x as the indenting value, which creates the diagonal effect required of this method. When the value of x is 1, the field width is 1, and the star is placed in that field width, right on the left margin. When x increases in value, the field width also increases, and the star is placed at the end of each larger field width, thus creating the diagonal effect.

Method 13 – reverseDiagonalNStars Lesson 6A - Loops51 WAM that will receive an integer parameter N and output a REVERSE diagonal of stars. Think about it, and good luck! Hint: Reverse the loop.

Method 14 – VofNStars Lesson 6A - Loops52 WAM that will receive an integer parameter N and output V shape of N stars. This is a kind of rite of passage for beginning programmers. It is a tough method, but if you think about it long enough, youll make it work. Heres a hint: Use one forward loop with two outputs inside the loop.

Method 15 – DiamondNStars Lesson 6A - Loops53 (BONUS) WAM that will receive an integer parameter N and output a diamond shape of N stars. Notice carefully that the top, bottom and sides of the diamond come to a single point.

As you did in the last lesson, when you finish this lab series, complete the documentation for all of the methods, run the JavaDoc utility, and print out and submit for a grade the API for your MyLoops class. Also print out and turn in the entire source code for this lab. JavaDoc Lesson 6A - Loops54

You have survived the first lesson on loops, probably the toughest lesson and lab series you have had so far. The Lesson 6B will tell you more about loops that count and accumulate values. CONGRATULATIONS! Lesson 6A - Loops55

Please copy, paste, and customize the brief acknowledgement shown below in an to indicating that you used this lesson. Feel free to include any comments you wish to offer, positive or negative. I, (your name), from (educational institution) in (city, state, country) used Lesson 6A on (date), understand, respect and honor all of the rights claimed by the author, Mr. John Owen, and offer the following comments..._______________. THANK YOU! Acknowledgement of use Lesson 6A - Loops56