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

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

Repetition and Loop Statements Chapter 5

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

Repetition Structures

REPETITION CONTROL STRUCTURE LOGO

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

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

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Introduction. C provides two styles of flow control:

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

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

Loops / Repetition Statements

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

Repetition Structures II

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

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Looping. Arizona State University 1

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

STUDENT LESSON A12 Iterations

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

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

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Dept. of CSE, IIT KGP

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Laboratory 5: Implementing Loops and Loop Control Strategies

CS1100 Introduction to Programming

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

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

Lecture 7 Tao Wang 1

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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

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

Increment and the While. Class 15

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

Chapter Goals. Contents LOOPS

Computer Science & Engineering 150A Problem Solving Using Computers

CS112 Lecture: Repetition Statements

Why Is Repetition Needed?

Chapter 4: Control structures. Repetition

3 The L oop Control Structure

Chapter 5: Loops and Files

CS110D: PROGRAMMING LANGUAGE I

Unit 3 Decision making, Looping and Arrays

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

Quiz Determine the output of the following program:

Loops / Repetition Statements

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Other Loop Options EXAMPLE

V3 1/3/2015. Programming in C. Example 1. Example Ch 05 A 1. What if we want to process three different pairs of integers?

Chapter 4: Control structures

Flow Control. CSC215 Lecture

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

LOOPS. Repetition using the while statement

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Computer Science & Engineering 150A Problem Solving Using Computers

CS112 Lecture: Loops

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

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

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

Information Science 1

Lecture 10. Daily Puzzle

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

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Chapter 5: Control Structures

Structured Program Development in C

A Look Back at Arithmetic Operators: the Increment and Decrement

Prepared by: Shraddha Modi

Control structure: Repetition - Part 2

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

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Chapter 3 Structured Program Development

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Chapter 4. Flow of Control

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

MODULE 2: Branching and Looping

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Programming Lecture 4

Chapter 5: Control Structures II (Repetition)

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

Information Science 1

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

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

Controls Structure for Repetition

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

DECISION CONTROL AND LOOPING STATEMENTS

Computer Programming I - Unit 5 Lecture page 1 of 14

Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

LECTURE 5 Control Structures Part 2

Control Structures II. Repetition (Loops)

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Transcription:

Chapter 5 While For 1 / 54 Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - s Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 While For 2 / 54 5.1 Repetition in Programs 5.2 Counting s and the While Statement 5.3 Computing a Sum or a Product in a 5.4 The for Statement 5.5 Conditional s 5.6 5.7 5.8 Do While Statement and Flag-Controlled s 5.10 How to Debug and Test 5.11 Common Errors cbourke@cse.unl.edu Repetition in Programs Counting s While For Just as the ability to make decisions (if-else selection statements) is an important programming tool, so too is the ability to specify the repetition of a group of operations. When solving a general problem, it is sometimes helpful to write a solution to a specific case. Once this is done, ask yourself: Were there any steps that I repeated? If so, which ones? Do I know how many times I will have to repeat the steps? If not, how did I know how long to keep repeating the steps? While For A counter-controlled loop (or counting loop) is a loop whose repetition is managed by a loop control variable whose value represents a count. Also called a while loop. 1 Set counter to an initial value of 0 2 while counter < somefinalv alue do 3 Block of program code 4 Increase counter by 1 5 end Algorithm 1: Counter-Controlled 3 / 54 4 / 54 The C While While Syntax While For This while loop computes and displays the gross pay for seven employees. The loop body is a compound statement (between brackets) The loop repetition condition controls the while loop. 1 int count_emp = 0; // Set counter to 0 2 while ( count_emp < 7) // If count_emp < 7, do stmts 4 printf (" Hours > "); 5 scanf ("%d",& hours ); 6 printf ("Rate > "); 7 scanf ("%lf",& rate ); 8 pay = hours * rate ; 9 printf (" Pay is $ %6.2 f\n", pay ); 10 count_emp = count_emp + 1; /* Increment count_emp */ 11 } 12 printf ("\ nall employees processed \n"); While For Syntax of the while Statement: Initialize the loop control variable Without initialization, the loop control variable value is meaningless. Test the loop control variable before the start of each loop repetition Update the loop control variable during the iteration Ensures that the program progresses to the final goal 1 count = 1; 2 while ( count <= 10) 4 printf (" Count = %d\n", count ); 5 count = count + 1; 6 } 5 / 54 6 / 54

Common Errors General While s While For Skipping crucial steps could lead to an infinite loop Common error: forgetting to increment your loop control variable Syntax error: misplaced semicolons 1 count = 1; 2 while ( count <= 10); WRONG 4 printf (" Count = %d\n", count ); 5 count = count + 1; 6 } While For Best to generalize code whenever possible 1 int numemployees, count_emp =0; 2 printf (" How many employees > "); 3 scanf ("%d", & numemployees ); 4 while ( count_emp < numemployees ) 5 { 6... 7 count_emp = count_emp + 1; 8 } Using numemployees instead of the constant 7 allows our code to be more general. 7 / 54 8 / 54 While While Answer While For Write a while loop to compute the sum of natural numbers 1 to 100: 100 i = 1 + 2 + + 100 i=1 Generalize the loop so that the sum from 1 to any n can be computed. Steps to design: Identify and define a loop control variable. Write the syntax for the loop control structure Fill in the code used within the loop to compute the sum While For 1 int sum = 0; 2 int i = 1; /* our loop control variable */ 3 while (i <= 100) 4 { 5 sum = sum + i; 6 i = i + 1; 7 } 8 printf (" Sum is %d\n", sum ); 9 / 54 10 / 54 While Answer: Generalized While Example II Instead of the sum of integers 1 to n, compute the product: While For 11 / 54 1 int sum = 0; 2 int n = 100; /* general variable, may be 3 * changed or read from input */ 4 int i = 1; /* our loop control variable */ 5 while (i <= n) 7 sum = sum + i; 8 i = i + 1; 9 } 10 printf (" Sum 1 to %d is %d\n", n, sum ); While For 12 / 54 100 i = 1 2... 100 i=1 What changes need to be made? Variable names? Initialized variable value? Operators? Note: this is the factorial function, n! = n i i=1

While Example II Answer Program Failed While For 1 int product = 1; 2 int n = 100; /* general variable, may be 3 * changed or read from input */ 4 int i = 1; /* our loop control variable */ 5 while (i <= n) 7 product = product * i; 8 i = i + 1; 9 } 10 printf (" Product 1 to %d is %d\n", n, product ); While For Run the previous program: it gives an answer of 0 why? Debug your code: use a printf statement in the loop to see what intermediate values are computed: printf("i = %3d product = %d\n",i,product); Check the answers with a calculator For what i does this program fail? 13 / 54 14 / 54 Overflow Operators While For We got the wrong answer for i = 13, 13! = 6, 227, 020, 800 We used a 32-bit integer to store product Maximum representable value is 2 31 = 2, 147, 483, 648 When a number is too large (or too small!) to be represented by its type, overflow occurs (or underflow) More sophisticated solutions are available, but outside this course s scope While For Expressions such as variable = variable op expression; (where op is a C operator such as +,-,*,/,) occur frequently C provides several syntax shortcuts x = x + 1; and x += 1; are equivalent Can do this with other operators (see table) Expression Shortcut x = x + 1; x += 1; x = x - 1; x -= 1; x = x * 5; x *= 5; x = x / 2; x /= 2; Table: Operators 15 / 54 16 / 54 Operators Example Revisited For s While For 1 int product = 1; 2 int n = 100; /* general variable, may be 3 * changed or read from input */ 4 int i = 1; /* our loop control variable */ 5 while (i <= n) 7 product *= i; 8 i += 1; 9 } 10 printf (" Product 1 to %d is %d\n", n, product ); While For Program Style Increment and Decrement Operators Increment and Decrement Other Than 1 17 / 54 18 / 54

For s For Example Computing the sum using a for-loop: While For Any repetition can be implemented using a while loop Another way to construct a counting loop is to use a for loop C provides for statements as another form for implementing loops. As before we need to initialize, test, and update the loop control variable. The syntax for a for statement is more rigid: it designates a specific place for the initialization, testing, and update components While For 1 int sum = 0; 2 int n = 100; 3 int i; 4 for (i = 0; i <= n; i ++) 5 { 6 sum += i; 7 } Advantages: more readable, more predictable Easier to debug Pitfall: note the placement of semicolons! 19 / 54 20 / 54 Increment Operators Program Style While For New syntax: i++ Known as a (postfix) increment Equivalent to i = i + 1 Also available: (postfix) decrement: i-- ( equivalent to i = i - 1) While For For clarity, the book usually places each expression of the for heading on a separate line. If all three expressions are very short, however, they will be placed on one line. The body of the for loop is indented just as the if statement. 21 / 54 22 / 54 Increment and Decrement Operators Increment and Decrement Other Than 1 While For The counting loops that we have seen have all included assignment expressions of the form counter = counter + 1 counter++ counter += 1 This will add 1 to the variable counter. Using -- will subtract one from the counter. While For We can use the shortcut compound assignment operators with values other than 1 Increment operations: sum = sum + x or sum += x, will take the value of sum, add x to it, and then assign the new value to sum Decrement operations: temp = temp - x or temp -= x, will take the value of temp, subtract x from it and then assign the new value to temp 23 / 54 24 / 54

Increment and Decrement Other Than 1 Example Conditional s While For 1 /* increment by 10 */ 2 int x = 10; 3 int i; 4 for (i=0; i <100; i+=x) 5 printf ("i = %d\n", i); 6 7 /* decrement by 5 */ 8 int y = 5; 9 for (i=25; i >=0; i -=y) 10 printf ("i = %d\n", i); While For The exact number of loop repetitions we need to run for a loop will not always be known before loop execution begins. Initialization step? Test? Update action? 25 / 54 26 / 54 Pseudocode While For Create a program that prompts the user for a value x and multiplies it by the previous value of x, storing the result in x, until the user enters a 0. While For 1 Set x to an initial value of 1 2 Prompt the user for a value input 3 while input is not zero do 4 Set x to x multiplied by input 5 Prompt the user for a new input value 6 end Algorithm 2: Prompt Product 27 / 54 28 / 54 Translated to C While For 1 int x = 1; 2 int value ; 3 printf (" Enter a value (0 to quit )> "); 4 scanf ("%d", & value ); 5 while ( value!= 0) 7 x = x * value ; 8 printf (" Enter a value (0 to quit )> "); 9 scanf ("%d", & value ); 10 } 11 printf (" The product is %d", value ); While For To this point, we have been analyzing the actions a loop performs. Now, we also want to design our own loops: Sentinel-Controlled s Using a for Statement to Implement a Sentinel 29 / 54 30 / 54

Sentinel-Controlled s Sentinel-Controlled s While For Often we don t know how many data items the loop should process when it begins execution. Sentinel-Controlled s continue to read data until a unique data value is read, called the sentinel value. The sentinel value should be a value that could not normally occur as data. Reading the sentinel value signals the program to stop reading and processing new data and exit the loop. Example: Product of a list of numbers, with 1 stopping the loop. While For 1 Get a line of data 2 while Sentinel value is not encountered do 3 Process the data 4 Get another line of data 5 end Algorithm 3: Product using a Sentinel 31 / 54 32 / 54 Implementing a Sentinel Implementing a Sentinel While Because the for statement combines the initialization, test, and update in once place, some programmers prefer to use it to implement sentinel-controlled loops. While For 1 int sentinelvalue = -1; 2 int score = 0 3 printf (" Enter first score (%d to quit )> ", sentinelvalue ); 4 for ( scanf ("%d", & score ); 5 score!= sentinelvalue ; 6 scanf ("%d", & score )) 7 { 8 sum += score ; 9 printf (" Enter next score (%d to quit )> ", sentinelvalue ); 10 } For scanf("%d",&score); Initialization: read the first score score!= sentinelvalue; Terminating condition (test) scanf("%d",&score) Update: read another score 33 / 54 34 / 54 Example While For Like if statements, loops can also be nested. Nested loops consist of an outer loop with or more inner loops. Each time the outer loop is repeated, the inner loops are reentered. The inner loop control expressions are reevaluated, and all required iterations are performed. While For 1 int i, j; 2 for (i=1; i <=10; i++) 4 for (j=1; j <=10; j++) 5 { 6 if(j<i) 7 printf ("+"); 8 else 9 printf ("*"); 10 } 11 printf ("\n"); 12 } 35 / 54 36 / 54

Example - Output The do-while Statement and Flag-Controlled s While For 1 ********** 2 +********* 3 ++******** 4 +++******* 5 ++++****** 6 +++++***** 7 ++++++**** 8 +++++++*** 9 ++++++++** 10 +++++++++* While For do-while statement flag-controlled loops 37 / 54 38 / 54 Statement Do While Example While For The for statement and the while statement evaluate conditions before the first execution of the loop body. In most cases, this pretest is desirable; Prevents the loop from executing when there are no data items to process Prevents execution when the initial value of the loop control variable is outside the expected range. Situations involving interactive input, when we know that a loop must execute at least one time, often use a do-while loop. While For 1 char letter_choice ; 2 do 4 printf (" Enter a letter from A through E> "); 5 scanf ("%c", & letter_choice ); 6 } while ( letter_choice < A letter_choice > E ); 39 / 54 40 / 54 Do While Flag-Controlled s While For begins with do Ends with while Careful: Conditional expression does end with a semicolon! Conditional is checked at the end of each loop (versus the beginning) While For Sometimes a loop repetition condition becomes so complex that placing the full expression in its usual spot is awkward. In many cases, the condition may be simplified by using a flag. A flag is a type int variable used to represent whether or not a certain event has occurred. A flag has one of two values: 1 (true) and 0 (false). 41 / 54 42 / 54

Flag Example How to Debug and Test Programs While For 1 char letter_choice ; 2 int isdone = 0; 3 while (! isdone ) 4 { 5 printf (" Enter a letter from A through E> "); 6 scanf ("%c", & letter_choice ); 7 isdone = ( letter_choice >= A && letter_choice <= E ); 8 } While For Debugging using printf Off-by-One Errors Testing 43 / 54 44 / 54 Debugging using printf Off-by-One Errors boundaries - the initial and final values of the loop control variable. While For Use several printf statements to output the values of your variables to make sure they have the correct value in them as your program executes. It is often helpful to print out the value of your loop control variable to make sure you are incrementing it and will not enter an infinite loop. While For A fairly common logic error in programs with loops is a loop that executes one more time or one less time than required. If a sentinel-controlled loop performs an extra repetition, it may erroneously process the sentinel value along with the regular data. If a loop performs a counting operation, make sure that the initial and final values of the loop control variable are correct and that the loop repetition condition is right. The sum of 1... 100, is not for(i = 1; i < 100; i++) sum += i; Instead, i <= 100 should be used. 45 / 54 46 / 54 Testing Common Errors I While For After all errors have been corrected and the program appears to execute as expected, the program should be tested thoroughly to make sure it works. For a simple program, make enough test runs to verify that the program works properly for representative samples of all possible data combinations. While For if and while statements can be confused, since they have similar appearance. Remember to initialize loop control variable as to prevent infinite loops. Infinite loops are bad: kill your program using control-c Remember to use brackets {... } around the code of the loop statements. 47 / 54 48 / 54

Common Errors II Real World Example While For Be careful about the loop conditions; if we only want positive results, then testing while (result!= 0) would not work since the result might become negative without ever being 0. A do-while loop always executes once and then tests the condition. While For Zune Bug: December 31st, 2008 2008 was a leap year: 366 days Thousands of Zunes froze for 24 hours An embedded module in the Zune contained the following (actual) code 49 / 54 50 / 54 Real World Example What happened? What happened? While For 1 while ( days > 365) 2 { 3 if ( IsLeapYear (year )) 4 { 5 if ( days > 366) 7 days -= 366; 8 year += 1; 9 } 10 } 11 else 12 { 13 days -= 365; 14 year += 1; 15 } 16 } While For If days (number of days since January 1, 1980) is 366 and year = 1980, then IsLeapYear(year) is true, but the nested if is not executed, so days is not ever changed and an infinite loop occurs This will happen on December 31 of any leap year http://bit-player.org/2009/the-zune-bug 51 / 54 52 / 54 Other Examples Questions While For September 30, 1999: $125 million Mars orbiter crashes due to lack of converting pounds of thrust to Newtons September 26, 1983: Stanislav Petrov averts nuclear war Russian missle early detection system alerts Petrov of incoming US missles; he correctly assumes that it s a bug since it s a new system and the size of the supposed attack is small Wired Article: History s Worst Software Bugs (http: //www.wired.com/software/coolapps/news/2005/11/69355) While For Questions? 53 / 54 54 / 54