David Stotts Computer Science Department UNC Chapel Hill.

Slides:



Advertisements
Similar presentations
Looping Structures: Do Loops
Advertisements

Roles of Variables with Examples in Scratch
CS0004: Introduction to Programming Repetition – Do Loops.
David Stotts Computer Science Department UNC Chapel Hill.
Objectives In this chapter, you will learn about:
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
Executes a statement or statements for a number of times – iteration. Syntax for(initialize; test; increment) { // statements to be executed } Initial.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Copyright © Texas Education Agency, Computer Programming For Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
David Stotts Computer Science Department UNC Chapel Hill.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Arrays After a while. Remember for loops? for(int i = 0; i < 10; i++){ System.out.println(i); } -But what if we are unsure of how many cycles we need?
Lecture Set 5 Control Structures Part D - Repetition with Loops.
Chapter 12: How Long Can This Go On?
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
CPS120 Introduction to Computer Science Iteration (Looping)
Using Shortcut Arithmetic Operators Accumulator: A variable that is used to total. Its value is repeatedly increased by some amount. Java provides shortcuts.
David Stotts Computer Science Department UNC Chapel Hill.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 6 Looping.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
Computer Science Department LOOPS. Computer Science Department Loops Loops Cause a section of your program to be repeated a certain number of times. The.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
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.
David Stotts Computer Science Department UNC Chapel Hill.
Visual Basic Programming
Coding Design Tools Rachel Gauci. Task: Counting On Create a program that will print out a sequence of numbers from "1" to a "number entered”. Decision’s.
David Stotts Computer Science Department UNC Chapel Hill.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 5A Repetition (Concepts)
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Control Structures RepetitionorIterationorLooping Part I.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
CPS120 Introduction to Computer Science Iteration (Looping)
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
David Stotts Computer Science Department UNC Chapel Hill.
Arrays and Loops. Learning Objectives By the end of this lecture, you should be able to: – Understand what a loop is – Appreciate the need for loops and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Loops and Arrays Chapter 19 and Material Adapted from Fluency Text book.
REPETITION CONTROL STRUCTURE
Lecture 6 Repetition Richard Gesick.
Programming Logic and Design Fourth Edition, Comprehensive
CHAPTER 5A Loop Structure
While Loops in Python.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Arrays, For loop While loop Do while loop
Introduction to Object-Oriented Programming with Java--Wu
Computing Fundamentals
Loops and Arrays in JavaScript
For loops Taken from notes by Dr. Neil Moore
FLUENCY WITH INFORMATION TECNOLOGY
Repetition Statements (Loops) - 2
While Loops in Python.
Presentation transcript:

David Stotts Computer Science Department UNC Chapel Hill

0. data (types, simple information) 1. data storage (variables, assignment) 2. data retrieval (expressions, evaluation) 3. repetition (loops) 4. decision making (conditionals) 5. procedure abstraction (functions) 6. data abstraction (arrays) 7. objects: all-the-above, wrapped up

 Often we need to “bump up” a variable value… add a little to what’s stored there  The pattern is to have the same variable name on both LHS and RHS of assignment  Here variable is “incremented” by 1 (all forms mean the same thing) x = x + 1 x += 1 x++  This form appears in loops often

 We can increment by more than 1’s x = x+2 x += 2 age = age+9 age += 9  We can increment by some variable amount, it doesn’t have to be just constants distance = distance + currMiles speed = speed + (time*accel) speed += time*accel

We can use more than just “+” (although the word “increment” is usually used for bumping up with addition) speed = speed * 2 speed *= 2 factorial = factorial * num factorial *= num

We can bump down a variable… decrement max = max – 1 max -= 1 one max-- highend = highend – 10 constant highend -= 10 upper = upper – num variable upper -= num upper = upper / 2

Repetition (loops)  Often we have a set of operations we would like to repeat over and over  We do this with loops (iteration)  World’s most famous loop: “ lather, rinse, repeat “

var first_num; // variable declaration var second_num; // variable declaration var total; // variable declaration first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); What if we want to repeat this a few times? Perhaps the user has more than one number pair to add

Cut and paste the code? var first_num; // variable declaration var second_num; // variable declaration var total; // variable declaration first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); It works, but … is it good?

var first_num; // variable declaration var second_num; // variable declaration var total; // variable declaration first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); 10 repetitions !! What if we need 100? 500,000 ? What if we want to repeat until the user is tired of it, or out of data? How many times will that be? Cut and paste on code lines clearly does not scale well

In a loop the syntax specifies two important components  the collection of program statements we want to repeat ( the loop body )  how many times to repeat the collection ( the number of iterations )

How to create a 20 tulip bouquet repeat // number of iterations 20 times all these steps { // body cut a tulip trim to proper length put it in the vase arrange to a pleasing look }

Human task example Spruce the train For // definite condition ( 11 times, one per car ) repeat { // body actions wash car windows grease wheel axles touch up car paint }

Human task example Spruce the train For start with car 1 stop after car 11 repeat { // body actions wash car windows grease wheel axles touch up car paint move to next car } “for” loops are a lot like this Work with a sequence

Definite loop: specific number of times, like counting items in a collection Concept for (N times) { do all these body statements} where N is some specific number ( this is NOT quite JavaScript syntax )

real JavaScript syntax var first_num; // variable declaration var second_num; // variable declaration var total; // variable declaration for (var i=1; i<=3; i++) { // says “do 3 times” // loop body is between the “curly braces” first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); } start stop Move to next time

Need to do this 500,000 times? var first_num; // variable declaration var second_num; // variable declaration var total; // variable declaration // user should get a cup of coffee and settle in … // here comes a LOT of data input typing for (var i=1; i<=500000; i++) { first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); } stop

Human task example Cut the Iron Bar while // indefinite condition (hot iron bar is one piece) repeat { // body actions heat bar red hot raise the hammer smack the chisel } How many hammer hits will it take? Who knows…

Indefinite loop: repeat the loop body an unpredictable number of times Concept while ( some condition holds ) { do all these body statements } ( this is NOT quite JavaScript syntax )

real JavaScript syntax var first_num; // variable declaration var second_num; // variable declaration var total; // variable declaration var more_input = “yes” ; // variable declaration while( more_input == “yes” ) { // loop body is between the “curly braces” first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); more_input = prompt(“do again? "); } Loop another time? Extra code does “Move to next” condition

real JavaScript syntax var first_num; // variable declaration var second_num; // variable declaration var total; // variable declaration var more_input = “yes” ; // variable declaration while( more_input == “yes” ) { first_num = Number(prompt(“First number? ")); second_num = Number(prompt(“Second number? “)); total = first_num + second_num; alert(“Their sum is “ + total); more_input = prompt(“do again? "); } User says “I’m done… let’s stop looping”

real JavaScript syntax var target; var counter = 2; var fact = 1; target = Number(prompt(“what number ?”)); while ( counter <= target ) { fact = fact * counter; counter = counter + 1; } alert(target + “ factorial is ” + fact); Data says “It’s done… stop the loop” not a user input, an internal variable change

In general … for loop: definite, specific # iterations while loop: indefinite, unknown # iterations ◦ loop until user says “I’m done” ◦ loop until data says “It’s done”

 Counter and Accumulator are common patterns of variable use  Remember the increment concept (or decrement) from earlier?  A counter is an increment inside a loop ◦ we usually increment by 1 (count by 1’s) but not always x = x + 1

var max; var kount = 0; // variable declaration // AND initialization combined max = Number(prompt(“what upper limit?”)); for (var i=1; i<=max; i++) { kount = kount + 1; } alert(“we counted to “ + kount); A counter MUST be initialized outside the loop, before the loop is entered and executed

 Accumulator : generalized counter  a counter in a loop is incremented by a variable amount  An accumulator is used to build a result incrementally -- one piece at a time ◦ we “grow” the result value some every time we execute the body of the loop result = result + i*offset factorial = factorial * num factorial *= num

var max; var fact = 1; // variable declaration // AND initialization combined max = Number(prompt(“factorial of what?”)); for (var i=1; i<=max; i++) { fact = fact * i; } alert(max + “ factorial is “ + fact); A multiply accumulator is initialized to 1 (why?)

var n; var total = 0; // variable declaration // AND initialization combined for (var i=1; i<=5; i++) { n = Number(prompt(“gimme a num”)); total = total + num; } alert(“5 user inputs sum to “ + total); An add accumulator is initialized to 0 (why?)