H1-1 University of Washington Computer Programming I Lecture 9: Iteration © 2000 UW CSE.

Slides:



Advertisements
Similar presentations
Solving Problems with Repetition. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly.
Advertisements

Repetition Control Structures
Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
CS150 Introduction to Computer Science 1
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Chapter 5 (Loop Statements)
©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.
Introduction to Computer Programming in c
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
do - while  while: Execute the body of the loop at least once
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
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.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Iterations Very Useful: Ability to repeat a block of code Example:
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
E-1 University of Washington Computer Programming I Lecture 5: Input and Output (I/O) © 2000 UW CSE.
9/29/99B-1 CSE / ENGR 142 Programming I Variables, Values, and Types © 1998 UW CSE.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
CISC105 – General Computer Science Class 4 – 06/14/2006.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
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.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Computer Programming -1-
Lesson #5 Repetition and Loops.
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
Lecture 7: Repeating a Known Number of Times
Lesson #5 Repetition and Loops.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Control Structures Lecture 7.
Looping.
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Control Structure Senior Lecturer
Lesson #5 Repetition and Loops.
Repetition and Loop Statements
Chapter 4 - Program Control
Week 6 CPS125.
Building Java Programs
Lesson #5 Repetition and Loops.
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

H1-1 University of Washington Computer Programming I Lecture 9: Iteration © 2000 UW CSE

H1-2 Overview Concepts this lecture Iteration - repetitive execution Loops and nested loops while statements for statements

H1-3 Chapter 5 Read Sections , Introduction While statement 5.4 For statement Loop design 5.7 Nested Loops 5.11 Common errors

H1-4 An Old Friend: Fahrenheit to Celsius #include int main(void) { double fahrenheit, celsius; printf("Enter a Fahrenheit temperature: "); scanf("%lf", &fahrenheit); celsius = (fahrenheit ) * 5.0 / 9.0; printf("That equals %f degrees Celsius.", celsius); return 0; }

H1-5 What’s “Wrong” with Fahrenheit/Celsius Program? User has to rerun the program for every new temperature Wouldn’t it be nice if the program could process repeated requests? Program ends immediately if user types a bad input Wouldn’t it be nice the program politely asked the user again (and again, etc. if necessary)?

H1-6 One More Type of Control Flow Sometimes we want to repeat a block of code. This is called a loop.

H1-7 Loops A “loop” is a repeated (“iterated”) sequence of statements Like conditionals, loops (iteration) give us a huge increase in the power of our programs Alert: loops are harder to master than if statements Even experienced programmers often make subtle errors when writing loops

H1-8 Motivating Loops Problem: add 4 numbers entered at the keyboard. int sum; int x1, x2, x3, x4; printf(“Enter 4 numbers: ”); scanf(“%d%d%d%d”, &x1, &x2, &x3, &x4); sum = x1 + x2 + x3 + x4;

H1-9 Motivating Loops Problem: add 4 numbers entered at the keyboard. int sum; int x1, x2, x3, x4; printf(“Enter 4 numbers: ”); scanf(“%d%d%d%d”, &x1, &x2, &x3, &x4); sum = x1 + x2 + x3 + x4; This works perfectly! But... what if we had 14 numbers? or 40? or 4000?

H1-10 Finding Repeated Code The key to using loops to solve a problem is to discover steps that can be repeated Our first algorithm for adding four numbers had no repeated statements at all But it does have some repetition buried in it. Let’s rework the algorithm to make the repetition more explicit

H1-11 Add 4 Numbers, Repetitively int sum, x; sum = 0; printf(“Enter 4 numbers: “); scanf(“%d”, &x); sum = sum + x;

H1-12 Loop to Add 4 Numbers int sum, x; sum = 0; printf(“ Enter 4 numbers :”); scanf(“%d”, &x); sum = sum + x; int sum, x; int count; sum = 0; printf(“ Enter 4 numbers:” ); count = 1; while (count <= 4) { scanf(“%d”, &x); sum = sum + x; count = count + 1; }

H1-13 More General Solution int sum, x, count; int number_inputs; /* Number of inputs */ sum = 0; printf(“How many numbers? “); scanf(“%d”, &number_inputs); printf(“Enter %d numbers: “, number_inputs); count = 1; while ( count <= number_inputs ) { scanf(“%d”, &x); sum = sum + x; count = count + 1; }

H1-14 while ( condition ) { statement1; statement2;... } while Statement Syntax Loop body: Any statement, or a compound statement Loop condition

H1-15 Compute 7! What is 1 * 2 * 3 * 4 * 5 * 6 * 7? (“seven factorial”) x = 1 * 2 * 3 * 4 * 5 * 6 * 7; printf ( “%d”, x ) ;

H1-16 Compute 7! What is 1 * 2 * 3 * 4 * 5 * 6 * 7? (“seven factorial”) x = 1 * 2 * 3 * 4 * 5 * 6 * 7; printf ( “%d”, x ) ; Bite size pieces:More Regular:As a loop: x = 1;x = 1;i = 2;x = 1; x = x * 2;x = x * i;i = i + 1;i = 2; x = x * 3; x = x * i;i = i + 1;while ( i <= 7 ) { x = x * 4;x = x * i;i = i + 1; x = x * i; x = x * 5;x = x * i;i = i + 1; i = i + 1; x = x * 6;x = x * i;i = i + 1;} x = x * 7;x = x * i;i = i + 1;

H1-17 i <= 7 ? x = x * i ; i = i + 1 ; yes no while Loop Control Flow x = 1 ; i = 2 ;

H1-18 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei xi  7? A?1 B21 C21T D22 E32 C32T C 6 120T D6720 E 7720 C 7720T D E C 85040F G (Print 5040)

H1-19 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei x A?1

H1-20 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei x A?1 B21

H1-21 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei xi  7? A?1 B21 C21T

H1-22 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei xi  7? A?1 B21 C21T D22 E32

H1-23 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei xi  7? A?1 B21 C21T D22 E32 C32T

H1-24 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei xi  7? A?1 B21 C21T D22 E32 C32T C 7720T D E 85040

H1-25 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei xi  7? A?1 B21 C21T D22 E32 C32T C 7720T D E C 85040F

H1-26 /* What is 1 * 2 * 3 *...*7 */ x = 1 ;/* A */ i = 2 ;/* B */ while ( i <= 7 ) { /* C */ x = x * i ;/* D */ i = i + 1 ;/* E */ }/* F */ printf ( “%d”, x ) ;/* G */ Tracing the Loop linei xi  7? A?1 B21 C21T D22 E32 C32T C 7720T D E C 85040F G (Print 5040)

H1-27 Double Your Money /* Suppose your $1,000 is earning interest at 5% per year. How many years until you double your money? */

H1-28 Double Your Money /* Suppose your $1,000 is earning interest at 5% per year. How many years until you double your money? */ my_money = ; n = 0; while ( my_money < ) { my_money = my_money *1.05; n = n + 1; } printf( “My money will double in %d years.”, n);

H1-29 printf ( “Enter values to average, end with -1.0 \n”) ; sum = 0.0 ; count = 0 ;sentinel scanf ( “%lf”, &next ) ; while ( next != -1.0 ) { sum = sum + next ; count = count + 1; scanf ( “%lf”, &next ) ; } if (count > 0) printf( “The average is %f. \n”, sum / (double) count ); Average Inputs

H1-30 Printing a 2-D Figure How would you print the following diagram?   repeat 3 times print a row of 5 stars repeat 5 times print  It seems as if a loop within a loop is needed.

H1-31 #define ROWS3 #define COLS5 … row = 1; while ( row <= ROWS ) { /* print a row of 5 *’s */ … row = row + 1; } Nested Loop

H1-32 row = 1; while ( row <= ROWS ) { /* print a row of 5 *’s */ col = 1; while (col <= COLS) { printf(“*”); col = col + 1; } printf( “\n” ); row = row + 1; } inner loop: print one row outer loop: print 3 rows Nested Loop

H1-33 Trace row: col: output: ***** ***** ***** row = 1; while ( row <= ROWS ) { /* print a row of 5 *’s */ col = 1; while (col <= COLS) { printf(“*”); col = col + 1; } printf( “\n” ); row = row + 1; }

H1-34 Print a Multiplication Table * 11 * 21 * 3 22 * 12 * 22 * 3 33 * 13 * 23 * 3 44 * 14 * 24 * 3

H Print Row 2 col = 1; while (col <= 3) { printf(“%4d”, 2 * col ); col = col + 1; } printf(“\n”); row number

H1-36 row = 1; while (row <= 4) { col = 1; while (col <= 3) { printf(“%4d”, row * col ); col = col + 1; } printf(“\n”); row = row + 1; } Nested Loops Print 4 rows Print one row

H1-37 rowcol 1 1print 1 2print 2 3print 3 print \n 2 1print 2 2print 4 3print 6 print \n Loop Trace rowcol 3 1print 3 2print 6 3print 9 print \n 4 1print 4 2print 8 3print 12 print \n

H1-38 Notes About Loop Conditions They offer all the same possibilities as conditions in if-statements Can use &&, ||, ! Condition is reevaluated each time through the loop A common loop condition: checking the number of times through the loop

H1-39 Counting Loops A common loop condition: checking the number of times through the loop Requires keeping a “counter” This pattern occurs so often there is a separate statement type based on it: the for-statement

H1-40 A for Loop /* What is 1 * 2 * 3 *... * n ? */ x = 1 ; i = 2 ; while ( i <= n ) { x = x * i ; i = i+1; } printf ( “%d”, x ) ; x = 1 ; for ( i = 2 ; i <= n ; i = i+1 ) { x = x * i ; } printf ( “%d”, x) ;

H1-41 for Statement Syntax for ( initialization; condition; update expression) { statement1; statement2;... }

H1-42 for Loop Control Flow Condition yes no For Loop Body Initialization Update Expression

H1-43 for Loops vs while Loops Any for loop can be written as a while loop These two loops mean exactly the same thing: for (initialization; condition; update) statement; initialization; while (condition) { statement; update; }

H1-44 Counting in for Loops /* Print n asterisks */ for ( count = 1 ; count <= n ; count = count + 1 ) { printf ( “*” ) ; } /* Different style of counting */ for ( count = 0 ; count < n ; count = count + 1 ) { printf ( “*” ); }

H1-45 #define ROWS3 #define COLS5... for ( row = 1; row <= ROWS ; row = row + 1 ) { for ( col = 1 ; col <= COLS ; col = col + 1 ) { printf( “  ” ); } printf( “\n” ); } “3 Rows of 5” as a Nested for Loop inner loop: print one row outer loop: print 3 rows

H1-46 Yet Another 2-D Figure How would you print the following diagram?      For every row ( row = 1, 2, 3, 4, 5 ) Print row stars

H1-47 Solution: Another Nested Loop #define ROWS 5... int row, col ; for ( row = 1 ; row <= ROWS ; row = row + 1 ) { for ( col = 1 ; col <= row ; col = col + 1) { printf( “  ” ) ; } printf( “\n” ); }

H1-48 Yet One More 2-D Figure How would you print the following diagram?      For every row ( row = 0, 1, 2, 3, 4) ) Print row spaces followed by (5 - row) stars

H1-49 Yet Another Nested Loop #define ROWS 5... int row, col ; for ( row = 0 ; row < ROWS ; row = row + 1 ) { for ( col = 1 ; col <= row ; col = col + 1) printf( “ ” ) ; for ( col = 1 ; col <= ROWS – row ; col = col + 1) printf( “  ” ) ; printf( “\n” ); }

H1-50 while ( sum < 10 ) ; sum = sum + 2; Some Loop Pitfalls for ( i = 1; i != 10 ; i = i + 2 ) sum = sum + i ; for ( i = 0; i <= 10; i = i + 1); sum = sum + i ;

H1-51 Double Danger double x ; for ( x = 0.0 ; x < 10.0 ; x = x ) printf(“%.18f”, x) ; Seems harmless...

H1-52 Double Danger What you expect: What you might get:

H1-53 int i ; double x ; for ( i = 0 ; i < 50 ; i = i + 1 ) { x = (double) i / 5.0 ; printf(“%.18f”, x) ; } Use ints as Loop Counters

H1-54 Counting in Loops Counting up by one or down by one: for ( i = 1 ; i <= limit ; i = i+1 ) {... } times_to_go = limit; while ( times_to_go > 0 ) { times_to_go = times_to_go - 1; }

H1-55 Counting Up or Down by 1 This pattern is so common there is special jargon and notation for it To "increment:" increase (often by 1) To "decrement:" decrease (often by 1) C operators: Post-increment ( x++ ): add 1 Post-decrement ( x-- ): subtract 1

H1-56 Handy Shorthand x++ x-- Used by itself, x++ means the same as x = x+1 x-- means the same as x = x-1 Very often used with loop counters: for ( i=1 ; i <= limit ; i++ ) {... } times_to_go = limit; while ( times_to_go > 0 ) {... times_to_go--...

H1-57 Surgeon General's Warning ++ and -- are unary operators. Pre-increment (++x) and pre-decrement (--x) exist, too. In this course, use ++ and -- only in isolation. Don't combine these with other operators in expressions! E.g., don't try x = y++ / (3 * --x--)

H1-58 Iteration Summary General pattern: Initialize, test, do stuff, repeat... “while” and "for" are equally general in C Use “for” when initialize/test/update are closely related and simple, especially when counting

H1-59 Looking Ahead We’ll talk more about how to design loops We’ll discuss complex conditional expressions Can be used with loops as well as in conditional statements We’ll see “arrays”, a powerful new way of organizing data Very often used with loops