CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10.

Slides:



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

Repeating Actions While and For Loops
Computer Science 1620 Loops.
Chapter 5 Repetition and Loop Statements Instructor: Alkar & Demirer.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 3, Lecture 2.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Control Structures II (Repetition)
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
CS 117 Spring 2002 Repetition Hanly Chapter 4 Friedman-Koffman Chapter 5.
Chapter 6 - Visual Basic Schneider1 Chapter 6 Repetition.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
An Object-Oriented Approach to Programming Logic and Design Chapter 6 Looping.
©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 Repetition Statements.
©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.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Programming Logic and Design Fifth Edition, Comprehensive
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
ARRAYS 1.Basic Ideas 2.The Array Type 3.Processing Arrays 4.Parallel Arrays 5.Two-dimensional Array 6.Arrays as Parameters.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 6 Looping.
Chapter 6 - Visual Basic Schneider 1 Chapter 6 Repetition.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
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.
Introduction to Pascal The Basics of Program writing.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Pascal Programming Pascal Loops and Debugging. Pascal Programming Pascal Loops In our first brush with the while do loops, simple comparisons were used.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Loops and Files. 5.1 The Increment and Decrement Operators.
Chapter 7 Problem Solving with Loops
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 11.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 5, Lecture 2 (Tuesday)
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 6, Lecture 1 (Monday)
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
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.
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.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (while) Outline 3.7The While Repetition.
REPETITION CONTROL STRUCTURE
Programming Logic and Design Fourth Edition, Comprehensive
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
( Iteration / Repetition / Looping )
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Control Structure Senior Lecturer
Repetition and Loop Statements
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

TODAY Finish loops (or almost) Homework #5 was posted on Monday Don’t wait to start on it!!!

Equivalent Statements FOR loop FOR Count := StartValue TO StopValue DO BEGIN... END {FOR} Equivalent WHILE Count := StartValue; WHILE Count <= StopValue DO BEGIN... ; Count := Count + 1; END {WHILE} Equivalent REPEAT Count := StartValue; IF StartValue <= StopValue THEN REPEAT... Count := Count + 1; UNTIL Count > StopValue

Simple Applications of FOR Lopps Printing patterns –E.g. diagonal band –E.g. tree Generating numbers (e.g. tables) –E.g. table of powers of numbers (sqr, sqrt, cubes) –E.g. Fibonacci numbers

Task: Draw Diagonal Band ***

Program: Diagonal Band PROGRAM DiagonalBand; VAR J : integer; BEGIN FOR J := 1 TO 8 DO writeln('***':J + 3); readln END.

Task: Draw Tree * * * **** * * ***

Program: Tree PROGRAM Tree; VAR J : integer; BEGIN writeln('*':5); FOR J := 1 to 3 DO writeln('*':5 - J,'*':2 * J); writeln('**** ****'); FOR J := 1 to 2 DO writeln('* *':6); writeln('***':6); readln END.

Task: Fibonacci Numbers Print the first 20 Fibonacci numbers Fibonacci numbers function:

Program: Fibonacci PROGRAM Fibonacci; CONST Number = 20; VAR J, {counter variable} N1, N2, N3 {counter variable} : integer; BEGIN N1 := 0; writeln('Fibonacci 0:', N1:5); N2 := 1; writeln('Fibonacci 1:', N2:5); FOR J := 2 TO Number – 1 DO BEGIN N3 := N1 + N2; writeln('Fibonacci',J:3,':',N3:5); N1 := N2; N2 := N3; END; readln END.

Output: Fibonacci Fibonacci 0: 0 Fibonacci 1: 1 Fibonacci 2: 1 Fibonacci 3: 2 Fibonacci 4: 3 Fibonacci 5: 5 Fibonacci 6: 8 Fibonacci 7: 13 Fibonacci 8: 21 Fibonacci 9: 34 Fibonacci 10: 55 Fibonacci 11: 89 Fibonacci 12: 144 Fibonacci 13: 233 Fibonacci 14: 377 Fibonacci 15: 610 Fibonacci 16: 987 Fibonacci 17: 1597 Fibonacci 18: 2584 Fibonacci 19: 4181

Simple Applications of WHILE/REPEAT loops Accumulators –E.g. sums, means, Simulations

Loop Design Terminology –Loop control: Making sure that the loop exits when it is supposed to –Loop processing: Making sure that the body performs the required operations To formulate loop control & loop processing, it is useful to list what we know about the loop

Loop Design Loop design can be approached in two ways: –Analyze requirements: Determine needed initialization, testing, and updating of the loop control variable Then formulate the loop control and loop processing steps –Develop templates: Make templates for frequently running forms Use these templates as the basis for the new loop

Sentinel-Controlled Loops Sentinel: –An end marker that follows the last data item Frequently, you will not know exactly how many data items a program will process before it begins execution One way to handle this is to instruct the user to enter a unique data value (sentinel value) as the last data item. The program then tests each data item and terminates when the sentinel value is read. Sentinel value should be carefully chosen and must be a value that could not normally occur as data.

Sentinel-Controlled Loops Template: Read the first value of input variable WHILE input variable is not equal to sentinel do BEGIN... Read next value of input variable END

Sentinel-Controlled Loops Example: Collecting Exam Scores: 1.Initialize Sum to 0 2.Read the first score into Score 3.WHILE Score is not the sentinel (e.g. -1) do BEGIN 4. Add Score to Sum 5. Read the next score into Score END

Loops Controlled by Boolean Flags Flag: A Boolean variable whose value is changed from False to True when a particular event occurs Boolean Flags Template: Initialize flag to false WHILE flag is still false DO BEGIN... Reset flag to true if event being monitored occurs END

Loops Controlled by Boolean Flags Example: Reading data characters and save the first digit character read DigitRead := false; WHILE ( not DigitRead ) DO BEGIN write ('Enter another data character >'); readln (NextChar); DigitRead := ('0'<=NextChar) AND (NextChar<='9') END {WHILE}

Task: Dropping Objects Problem definition: –Your physics professor wants you to write a program that displays the effect of gravity on a free-falling object. You should build a table showing the height from a tower to every second.

Analysis: Dropping Objects Observations: –Assume time of free fall = t –At t = 0.0 {initialization} object height = tower height –While falling {updating-loop body} object height = tower height - distance traveled –Free fall ends{testing -exit} when height <= 0.0

Program Segment: Dropping Objects writeln ('Time' :10:2, 'Height' 10:2); {initialization} T := 0.0; Height := Tower; WHILE Height > 0.0 DO BEGIN {body} writeln (T : 10:2, Height :10:2); T := T + DeltaT; Height := Tower * G * Sqr(T) END {WHILE} writeln; writeln ('SPLATT!!!');

Example: Dropping Objects Observations –Before the loop is entered, a message displaying the heading is printed. –The number of lines in the table depends on the time interval between lines (DeltaT) and the tower height (Tower). –During each loop iteration, the current elapsed time, t, and the current object height are displayed and new values are assigned to these variables.

Simple Loops Summary Use FOR loop as a counting loop. The loop control variable must belong to an ordinal type (not real). REPEAT and WHILE-loops are conditional loops. Their number of iteration depends on whether the value of a condition is true or false. WHILE loop is repeated as long as its loop repetition condition is true. REPEAT loop is repeated until its loop-termination condition becomes true. Usually a REPEAT loop can be written as a WHILE loop by complementing the condition. Not all WHILE loops can be written as REPEAT loops, because REPEAT loops executes at least once, whereas a WHILE loop body may be skipped entirely. WHILE loop is preferred over a REPEAT loop unless you are certain that at least one loop iteration must always be performed.

Exercises Write a while loop that counts the number of digits entered in a stream of characters. Exit when the character ‘X’ is entered. Make sure you don’t count the X Write a while loop that reads negative or positive numbers, keeping track of the largest in absolute terms. Exit when a zero is entered. Write a while loop that reads lines of text, and counts the characters entered. Exit when the string ‘Quit’ is entered. (Don’t count the characters in ‘Quit’).

Nested Loops It is possible to nest loops Each time the outer loop is repeated, the inner loops are reentered, their loop-control parameters are reevaluated, and all required iterations are performed Very useful in processing multi-dimensional arrays

Task: Draw Isosceles Triangle * *** ***** ******* *********

Program: Isosceles Triangle PROGRAM Triangle; {Draw an isosceles triangle} CONST NumLines = 5;{number of rows in triangle} Blank = ' '; {output character} Star = '*'; {output character} VAR Row, {control for outer loop} LeadBlanks, {control for first inner loop} CountStars: integer; {control for 2nd inner loop} {Continued}

Nested Loops Example Isosceles Triangle BEGIN {Triangle} FOR Row := 1 TO NumLines DO{outer loop} BEGIN {Draw each row} {first inner loop} FOR LeadBlanks := NumLines - Row DOWNTO 1 DO write (Blank);{Print leading blanks} {second inner loop} FOR CountStars := 1 TO 2 * Row - 1 DO write (Star);{Print asterisks} writeln; END {for Row} end. {Triangle}