Iteration. CSE / ENGR 142 Programming I. while loops. Chapter 5. Motivating Loops. Loop to Add 5 Numbers 1996 UW CSE H - 1

Similar documents
Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. One More Type of Control Flow. What s Wrong with HW1?

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. What s Wrong with Fahrenheit/Celsius Program? One More Type of Control Flow

CPE 101 slides adapted from UW course. Overview. Chapter UW CSE H1-1. An Old Friend: Fahrenheit to Celsius. Concepts this lecture

n Group of statements that are executed repeatedly while some condition remains true

Dept. of CSE, IIT KGP

Repetition and Loop Statements Chapter 5

Looping. Arizona State University 1

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

A Look Back at Arithmetic Operators: the Increment and Decrement

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Chapter 5: Loops and Files

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Decision Making and Loops

STUDENT LESSON A12 Iterations

REPETITION CONTROL STRUCTURE LOGO

Chapter 4: Control structures. Repetition

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Loops / Repetition Statements

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Chapter 4: Control structures

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Introduction. C provides two styles of flow control:

Prepared by: Shraddha Modi

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

CS110D: PROGRAMMING LANGUAGE I

Programming for Engineers Iteration

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Conditionals. CSE / ENGR 142 Programming I. Chapter 4. Conditional Execution. Conditional ("if ") Statement. Conditional Expressions

Unit 3 Decision making, Looping and Arrays

Technical Questions. Q 1) What are the key features in C programming language?

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Loops. CSE 114, Computer Science 1 Stony Brook University

Use of scanf. scanf("%d", &number);

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition Structures II

Structured Programming. Dr. Mohamed Khedr Lecture 9

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Repetition Structures

Control Structures II. Repetition (Loops)

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

بسم اهلل الرمحن الرحيم

Arrays. CSE / ENGR 142 Programming I. Chapter 8. Another Motivation - Averaging Grades. Motivation: Sorting. Data Structures.

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C++ Programming: From Problem Analysis to Program Design, Third Edition

Loops / Repetition Statements

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Loops (while and for)

Computer Programming & Problem Solving ( CPPS )

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

AMCAT Automata Coding Sample Questions And Answers

Outline for Today CSE 142. Programming a Teller Machine. CSE142 Wi03 I-1. ATM Algorithm for Dispensing Money

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Lecture 10. Daily Puzzle

Java Coding 3. Over & over again!

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

CSE / ENGR 142 Programming I

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Chapter 5: Control Structures

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Fundamentals of Computer Programming Using C

Branching is deciding what actions to take and Looping is deciding how many times to take a certain action.

Chapter Goals. Contents LOOPS

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Chapter 3 Structured Program Development in C Part II

Information Science 1

Information Science 1

Lecture 7 Tao Wang 1

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

204111: Computer and Programming

LOOPS. Repetition using the while statement

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Control Structure: Loop

Display Input and Output (I/O)

Overview. CS 201 Repetition. Endfile-controlled loops. What is the Output? Nested Loops. Loops. Debzani Deb

Lecture 6. Statements

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Module 4: Decision-making and forming loops

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

DECISION MAKING STATEMENTS

All about flow control

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Top-Down Program Development

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Transcription:

CSE / ENGR 142 Programming I Iteration Chapter 5 Read Sections 5.1-5.6, 5.10 5.1 Introduction & While Statement 5.2 While example 5.3 For Loop 5.4 Looping with a fixed bound 5.5 Loop design 5.6 Nested Loops 5.10 Debugging Loops 1999 UW CSE H-1 H-2 Motivating Loops Loop to Add 5 Numbers Problem: add 5 numbers entered at the keyboard. Here s a solution: int sum; int x1, x2, x3, x4, x5; printf( Enter 5 numbers: ); scanf( %d%d%d%d%d, &x1, &x2, &x3, &x4, &x5); sum = x1 + x2 + x3 + x4 + x5; This works perfectly! But what if we had 15 numbers? or 50? or 5000? int sum, x; sum = 0; printf( Enter 5 numbers: ); int sum, x; int count; sum = 0; printf( Enter 5 numbers: ); count = 1; while (count <= 5) { count = count + 1; H-3 H-4 More General Solution while loops int sum; int x; int 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 ) { count = count + 1; H-5 loop condition while ( condition ) { statement1; statement2; loop body H-6 H - 1

Compute 9! While Loop Control What is 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9? ("nine factorial") x = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 ; printf ( %d, x ) ; x = 1 ; i = 2 ; Bite size pieces: More Regular: Better Still: 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 <= 9 ) { x = x * 4; x = x * i; i = i + 1; x = x * i; i = i + 1; x = x * 9; x = x * i; i = i + 1; i <= 9? no yes x = x * i ; i = i + 1 ; H-7 H-8 Tracing the Loop Double Your Money /* What is 1 * 2 * 3 * * 9? */ # i product i 9? A? 1 product = 1 ; /* A */ B 2 1 i = 2 ; /* B */ C 2 1 T while ( i <= 9 ) { /* C */ D 2 2 product = product * i ; /* D */ E 3 2 i = i + 1 ; /* E */ C 3 2 T /* F */ D 3 6 printf ( %d, product ) ; /* G */ E 4 6 C 4 6 T D 4 24 E 10 362880 C 10 362880 F G ( print 362880 ) /* Suppose your $1,000 is earning interest at 5% per year. How many years until you double your money? */ my_money = 1000.0; n = 0; while ( my_money < 2000.0 ) { my_money = my_money *1.05; n = n + 1; printf( My money will double in %d years., n); H-9 H-10 Average Inputs Printing a 2-D Figure printf ( Enter numbers 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 ); How would you print the following diagram? repeat 3 times print a row of 5 stars repeat 5 times print H-11 H-12 H - 2

Nested Loop Nested Loop outer print 3 rows #define ROWS 3 #define COLS 5 row = 1; while ( row <= ROWS ) { /* print a row of 5 * s */ row = row + 1 outer print 3 rows row = 1; while ( row <= ROWS ) { /* print a row of 5 * s */ col = 1; while (col <= COLS) { printf( * ); col = col + 1; row = row + 1; (#defines omitted to save space) inner print one row H-13 H-14 Trace Print a Multiplication Table row: col: 1 2 2 4 6 3 3 6 9 4 4 8 12 1 1 * 1 1 * 2 1 * 3 2 2 * 1 2 * 2 2 * 3 3 3 * 1 3 * 2 3 * 3 4 4 * 1 4 * 2 4 * 3 output: H-15 H-16 Print Row 2 Nested Loops 1 2 3 4 2 4 6 3 6 9 4 8 12 col = 1; while (col <= 3) { printf( %4d, 2 * col ); col = col + 1; printf( \n ); row number row = 1; while (row <= 4) { col = 1; while (col <= 3) { printf( %4d, row * col ); col = col + 1; printf( \n ); row = row + 1; Print 4 rows Print one row H-17 H-18 H - 3

Loop Trace Loop Trace (Detailed) row col 1 1 print 1 2 print 2 3 print 3 2 1 print 2 2 print 4 3 print 6 3 1 print 3 2 print 6 3 print 9 4 1 print 4 2 print 8 3 print 12 row col statement 1? 1a 1? (TRUE) 1b 1 1 2a 1 1 (TRUE) 2b 1 1 print 1 3 1 2 2c 1 2 (TRUE) 2b 1 2 print 2 3 1 3 2c 1 3 (TRUE) 2b 1 3 print 3 3 1 4 2c 1 4 (FALSE) 2b 1 4 4 2 4 1c 2 4 (TRUE) 1b 2 1 2a H-19 H-20 for Loops for Loops Syntax /* What is 1 * 2 * 3 * * n? */ product = 1 ; i = 2 ; /* initialize */ product = 1 ; while ( i <= n ) { /* test */ for ( i = 2 ; i <= n ; i = i+1 ) { product = product * i ; product = product * i ; i = i+1; /* update */ printf ( %d, product ) ; printf ( %d, product ) ; for ( initialization; condition; update expression ) { statement1; statement2; Update is written at the front of the loop, but executed at the end H-21 H-22 for Loop Control Flow Counting in for Loops Initialization yes condition no For Loop Body Update Expression /* 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 ( * ); /* could also use count <= n-1 */ H-23 H-24 H - 4

Another 2-D Figure Puzzle Print the following diagram with a for loop repeat 3 times print a row of 5 stars repeat 5 times print Nested Loop outer print 3 rows #define ROWS 3 #define COLS 5 for ( row = 1; row <= ROWS ; row = row + 1 ) { for ( col = 1 ; col <= COLS ; col = col + 1 ) { printf( ); inner print one row H-25 H-26 Trace Yet Another 2-D Figure How would you print the following diagram? row: col: output: For every row ( row = 1, 2, 3, 4, 5 ) Print row stars H-27 H-28 Solution: Another Nested Loop Trace #define ROWS 5 int row, col ; for ( row = 1 ; row <= ROWS ; row = row + 1 ) { for ( col = 1 ; col <= row ; col = col + 1) { printf( ) ; row: col: output: H-29 H-30 H - 5

Yet One More 2-D Figure Yet Another Nested Loop How would you print the following diagram? For every row ( row = 0, 1, 2, 3, 4) Print row spaces followed by (5 - row) stars #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( ) ; H-31 H-32 The Appeal of Functions Multiplication Table, again /* Print character symbol n times */ void repeat_chars ( int n, char symbol) { int i ; for ( i = 1 ; i <= n ; i = i + 1 ) printf ( %c, symbol ) ; for ( row = 0 ; row < ROWS ; row = row + 1 ) { repeat_chars ( row, ) ; repeat_chars ( ROWS - row, ) ; H-33 1 2 2 4 6 3 3 6 9 4 4 8 12 1 1 * 1 1 * 2 1 * 3 2 2 * 1 2 * 2 2 * 3 3 3 * 1 3 * 2 3 * 3 4 4 * 1 4 * 2 4 * 3 H-34 Print Row 2 Nested Loops 1 2 2 4 6 3 3 6 9 Print one row 4 4 8 12 for (col = 1; col <= 3; col = col + 1) { printf( %4d, 2 * col ); printf( \n ); row number H-35 1 2 2 4 6 3 3 6 9 Print 4 rows 4 4 8 12 for (row = 1; row <= 4; row = row + 1 ) { Print one row for (col = 1; col <= 3; col = col + 1) { printf( %4d, row * col ); printf( \n ); H-36 H - 6

Nested Loops #define ROWS 4 #define COLUMNS 3... int row, col ; for (row = 1; row <= ROWS; row = row + 1) { /* 1 a,b,c */ for (col = 1; col <= COLUMNS; col = col + 1) { /* 2 a,b,c */ printf( %4d, row * col ) ; /* 3 */ printf( \n ) ; /* 4 */ 2 4 6 3 6 9 4 8 12 H-37 Loop Trace row col 1 1 print 1 2 print 2 3 print 3 2 1 print 2 2 print 4 3 print 6 3 1 print 3 2 print 6 3 print 9 4 1 print 4 2 print 8 3 print 12 H-38 Loop Trace (Detailed) row col statement 1? 1a 1? (TRUE) 1b 1 1 2a 1 1 (TRUE) 2b 1 1 print 1 3 1 2 2c 1 2 (TRUE) 2b 1 2 print 2 3 1 3 2c 1 3 (TRUE) 2b 1 3 print 3 3 1 4 2c 1 4 (FALSE) 2b 1 4 4 2 4 1c 2 4 (TRUE) 1b 2 1 2a Some Loop Pitfalls while ( sum < 10 ) ; for ( i = 0; i <= 10; i = i + 1) ; sum = sum + 2; sum = sum + i ; for ( i = 1; i!= 10 ; i = i + 2 ) sum = sum + i ; double x ; for ( x = 0.0 ; x < 10.0 ; x = x + 0.2 ) printf( %.18f, x) ; H-39 H-40 Double Delight Use ints as Loop Counters What you expect: What you might get: 0.000000000000000000 0.000000000000000000 0.200000000000000000 0.200000000000000000 0.400000000000000000 0.400000000000000000 9.000000000000000000 8.999999999999999997 9.200000000000000000 9.199999999999999996 9.400000000000000000 9.399999999999999996 9.600000000000000000 9.599999999999999996 9.800000000000000000 9.799999999999999996 9.999999999999999996 int i ; double x ; for ( i = 0 ; i < 50 ; i = i + 1 ) { x = (double) i / 5.0 ; printf( %.18f, x) ; H-41 H-42 H - 7

Counting in Loops To "increment:" increase (often by 1) To "decrement:" decrease (often by 1) Many loops increment or decrement a loop counter: for ( i = 1 ; i <= limit ; i = i+1 ) {... Handy Shorthand Post-increment ( x++ ), Post-decrement ( x-- ) Used by itself, x++ means the same as x = x+1 x-- means the same as x = x-1 for ( i=1 ; i <= limit ; i++ ) {... times_to_go = limit; while ( times_to_go > 0 ) { times_to_go = times_to_go - 1; H-43 times_to_go = limit; while ( times_to_go > 0 ) { times_to_go-- ; H-44 Surgeon General s Warning ++ and -- are unary operators. Pre-increment (++x) and pre-decrement (--x) exist, too. For now, use only in isolation. Don t combine these with other operators in expressions! E.g., don t try x = y++ / (3 * --x--) Iteration Summary General pattern: initialize test do stuff update go back to re-test, re-do stuff, re-update, while and "for" are equally general in C use for when initialize/test/update are simple, especially when counting H-45 H-46 Event-Driven Programming Modern programs tend to be "eventdriven" Program starts, sets itself up. Waits for some event or command to happen: mouse click, key click, timer, menu selection, etc. Program performs operation ("handles" the command) Program goes back to waiting GP142 programs follow this model H-47 Simple Command Interpreter Read in "commands" and execute them. Input - single characters a -- execute command A by calling A_handler( ) b -- execute command B by calling B_handler( ) q -- quit Pseudocode for main get next command if a, execute command A if b, execute command B if q, signal quit H-48 H - 8

Command Interpreter Loop Control Command Interpreter Program #define FALSE 0 #define TRUE 1 int main(void) { char command; int done; done = FALSE; repeat until quit signal use variable done to indicate when done set done to false while not done body statements if quit command, set done to true H-49 while (! done){ /* Input command from user */ printf( Input command: ); scanf( %c, &command); switch (command){ case A : case a : A_handler(); /* Execute command A */ break; case B : case b : B_handler(); /* Execute command B */ break; case Q : case q : done = TRUE; /* User wants to quit */ break; default: printf( Unrecognized command\n ); return 0; H-50 switch example revisited #define TRUE 1 #define FALSE 0 char marital_status ; int valid; valid = FALSE; while (! valid) { printf ( Enter Marital status (M,S): ) ; scanf ( %c, &marital_status ) ; switch ( marital_status ) { case m : case M : valid = TRUE; printf ( Married \n ) ; break ; case s : case S : valid = TRUE; printf ( Single \n ) ; break ; default: printf ( Sorry, I don t recognize that code. \n ) ; H-51 H - 9