Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.

Slides:



Advertisements
Similar presentations
Outline 5.1 REPETITION IN PROGRAMS
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Computer Science 1620 Loops.
CS201 - Repetition loops.
Chapter 5 Repetition and Loop Statements Instructor: Alkar & Demirer.
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.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 CS 201 Repetition Debzani Deb. 2 Overview Loops  Endfile-Controlled loop  Nested loop  Do-While loop  Flag-Controlled loop Hand Tracing the code.
CS 201 Selection Structures (2) and Repetition
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 5 (Loop Statements)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Chapter 5 Repetition and Loop Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Repetition in the programs Example 1: Suppose we want to display the consecutive digits: 0,1,2,….9. For doing that adding one to the previous number should.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5: Control Structures II (Repetition)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Unit 4 Repetition and Loops. Key Concepts Flowcharting a loop Types of loops Counter-controlled loops while statement Compound assignment operator for.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 ICS103 Programming in C Ch5: Repetition and Loop Statements.
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.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Chapter 5 Repetition and Loop Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville,
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 12: Control Flow. Repetition and Loop structures COS120 Software Development Using C++ AUBG, COS dept.
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.
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.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
1 ICS103 Programming in C Lecture 7: Repetition Structures.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
H1-1 University of Washington Computer Programming I Lecture 9: Iteration © 2000 UW CSE.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
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.
CHAPTER 4 REPETITION STRUCTURES 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Asma Alosaimi.
Repetition statements
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
ICS103 Programming in C Lecture 7: Repetition Structures
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
REPETITION STATEMENTS
Repetition and Loop Statements
Control Statements Loops.
Chapter 6: Repetition Statements
Repetition and Loop Statements
Control Statements Loops.
Chapter 4 Repetition Structures
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin

Repetition Loop – The repetition of steps in a program Loop body – The statements that are repeated in the loop Dr. Chow-Sing Lin2Repetition and Loop Statement - CH 5

Repetition (Cont.) Dr. Chow-Sing Lin3Repetition and Loop Statement - CH 5

Loop Kinds KindWhen Used C Implementation Structures Counting loopWe can determine before loop execution exactly how many loop repetitions will be needed to solve the problem while for Sentinel-controlled loopInput of a list of data of any length ended by a special value while, for Endfile-controlled loopInput of a single list of data of any length from a data file while, for Input validation loopRepeated interactive input of a data value until a value within the valid range is entered do-while General conditional loopRepeated processing of data until a desired condition is met while, for Dr. Chow-Sing LinRepetition and Loop Statement - CH 54

Counting Loop Counter-controlled loop (Counting loop) – A loop whose required number of iterations can be determined before loop execution begins Dr. Chow-Sing LinRepetition and Loop Statement - CH 55 Set loop control variable to an initial value of 0 while loop control variable < final value …… Increase loop control variable by 1

while Statement SYNTAX Dr. Chow-Sing LinRepetition and Loop Statement - CH 56 while (loop repetition condition) statement /* Display N asterisks. */ count_star = 0; while (count_star < N) { printf(“*”); count_star = count_star + 1; } Example

while Statement (Cont.) Computes and displays the gross pay for seven employees – Count_emp : loop control variable Dr. Chow-Sing LinRepetition and Loop Statement - CH 57 Loop repetition condition statement After seven weekly pay amounts are displayed

while Statement (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 58

Exercises Predict the output of this program fragment : Dr. Chow-Sing LinRepetition and Loop Statement - CH 59 i = 0; while (i <= 5) { printf(“%3d %3d\n”, i, 10 – i); i = i + 1; } output

Loop control variable Determine whether the loop body is repeated Initialization – count_emp is set to an initial value of 0 before the while statement is reached Initialized to 0 Testing – count_emp is tested before the start of each loop repetition Called an iteration or a pass Updating – count_emp is updated (its value increased by 1) during each iteration Dr. Chow-Sing LinRepetition and Loop Statement - CH 510

Infinite loop If the loop control variable is not updated – The loop will execute “forever” A loop that executes forever Dr. Chow-Sing LinRepetition and Loop Statement - CH 511

Computing a Sum in a Loop Dr. Chow-Sing LinRepetition and Loop Statement - CH 512 Accumulator : a variable used to store a value being computed in increments during the execution of a loop

Enter number of employees> 3 Hours> 50 Rate> $5.25 Pay is $ Hours> 6 Rate> $5.00 Pay is $30.00 Hours> 15 Rate> $7.00 Pay is $ All employees processed Total payroll is $ Dr. Chow-Sing LinRepetition and Loop Statement - CH 513

Computing a Sum in a Loop (Cont.) Statementhoursratepaytotal_paycount_empEffect ???0.00 count_emp < number_emp true scanf (“%lf”, &hours); 50.0get hours scanf (“%lf”, &rate); 5.25get rate pay = hours * rate; 262.5find pay total_pay = total_pay + pay 262.5add to total_pay count_emp = count_emp +1 1Increment count_emp count_emp < number_emp true scanf (“%lf”, &hours); 6.0get hours scanf (“%lf”, &rate); 5.0get rate pay = hours * rate; 30.0find pay Dr. Chow-Sing LinRepetition and Loop Statement - CH 514

Computing a Sum in a Loop (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 515 Statementhoursratepaytotal_paycount_empEffect total_pay = total_pay + pay 292.5add to total_pay count_emp = count_emp +1 2Increment count_emp count_emp < number_emp true scanf (“%lf”, &hours); 15.0get hours scanf (“%lf”, &rate); 7.0get rate pay = hours * rate; 105.0find pay total_pay = total_pay + pay 397.5add to total_pay count_emp = count_emp +1 3Increment count_emp

Computing a Product in a loop Example 5.2 – The loop that follows multiplies data items together as long as the product remains less than 10,000 – Before asking for the next data value, it displays the product calculated so far Dr. Chow-Sing LinRepetition and Loop Statement - CH 516 /* Multiply data while product remains less than */ product = 1; while (product “); scanf(“%d”, &item); product = product * item; /* Update product */ }

Compound Assignment Operators variable = variable op expression – op is a C arithmetic operator – Increments and decrements of loop counters count_emp = count_emp + 1; time = time – 1; – Statements accumulating a sum or a computing a product in a loop total_pay = total_pay +pay; product = product * item; Dr. Chow-Sing LinRepetition and Loop Statement - CH 517

Compound Assignment Operators (Cont.) Statement with Simple Assignment Operator Equivalent Statement with Compound Assignment Operator count_emp = count_emp + 1;count_emp += 1; time =time – 1 ;time -= 1; total_time = total_time + time;total time += time; product = product * item;product *= item; n = n * (x + 1);n *= x + 1; Dr. Chow-Sing LinRepetition and Loop Statement - CH 518

The for Statement loop control components – Initialization of the loop control variable – Test of the loop repetition condition – Change (update) of the loop control variable Syntax Dr. Chow-Sing LinRepetition and Loop Statement - CH 519 for (initialization expression; loop repetition condition; update expression) statement

The for Statement (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 520 for (count_emp = 0 ;/* initialization */ count_emp < number_emp; /* loop repetition condition */ count_emp += 1) /* update */ Example /* Display N asterisks. */ for (count_star = 0; count_star < N; count_star += 1) printf (“*”); Example

Increment and Decrement Operator Increment operator “++” – The value of its operand is incremented by one Prefix increment – “++” is placed immediately in front of its operand (++a) – The value of the expression is the variable ‘s value after incrementing Postfix increment – “++” comes immediately after the operand (a++) – the expression’s value is the value is the value of the variable before it is incremented Dr. Chow-Sing LinRepetition and Loop Statement - CH 521

Increment and Decrement Operator (Cont.) Given an initial value of 2 in i Dr. Chow-Sing LinRepetition and Loop Statement - CH 522

Function to Compute Factorial Dr. Chow-Sing LinRepetition and Loop Statement - CH 523

Increments and Decrements Other Than 1 Example 5.4 – Temperature conversions from 10 degrees Celsius to -5 degrees Celsius – The values of the constant macros named CBEGIN and CLIMIT – Loop update step Subtracts CSTEP(5) from Celsius – When Celsius becomes less than CLIMIT Loop exit (Celsius is -10) Dr. Chow-Sing LinRepetition and Loop Statement - CH 524

Figure 5.8 Displaying a Celsius-to- Fahrenheit Conversion Table Dr. Chow-Sing LinRepetition and Loop Statement - CH 525

Review Question I Trace the execution of the loop – n = 8 – Show values of odd and sum After the update of the loop counter for each iteration Dr. Chow-Sing LinRepetition and Loop Statement - CH 526 sum = 0; for (odd = 1; odd < n; odd += 2) sum = sum + odd; printf(“Sum of positive odd numbers less than %d is %d. \n”, n, sum);

Review Question I (Cont.) StatementoddsumEffect sum = 0;0Initialize sum to 0 odd = 11Initialize odd to 1 odd < n;1 < 8 is true sum += odd;1sum = odd += 23odd = odd < n;3 < 8 is true sum += odd;4sum = odd += 25odd = odd < n;5 < 8 is true sum += odd;9sum = odd += 27odd = odd < n;7 < 8 is true Dr. Chow-Sing LinRepetition and Loop Statement - CH 527 For n = 8 :

Review Question I (Cont.) StatementoddsumEffect sum += odd;16sum = odd += 29odd = odd < n;9 < 8 is false Exit loop printf (“Sum of…Output : Sum of positive odd numbers less than 8 is 16 Dr. Chow-Sing LinRepetition and Loop Statement - CH 528

Review Question II Rewrite the code – No increment / decrement operator appears in an expression with another arithmetic operator Dr. Chow-Sing LinRepetition and Loop Statement - CH i; --j; n = i * j; m = i + j; j--; p = i + j; n = ++i * --j; m = i + j--; p = i + j; Rewrite

Conditional Loops Not know in advance how many times the loop would execute Example – Continue prompting the user for a data value as long as the response is unreasonable. – Write this validating input loop in C with a while statement Dr. Chow-Sing LinRepetition and Loop Statement - CH 530 printf(“Enter number of observed values> “); scanf(“%d”, &num_obs); /* initialization */ while (num_obs “); scanf(“%d”, &num_obs); /* update */ }

Loop Design Sentinel-Controlled Loops Question – Many programs with loops input one or more additional data item is repeated – Often we don’t know how many data items the loop should process Solution – Sentinel value User to enter a unique data value An end marker that follows the last item in a list of data Dr. Chow-Sing LinRepetition and Loop Statement - CH 531

Sentinel-Controlled Loops (Cont.) When the sentinel value is read – The loop repetition condition tests each item and cause loop exit – It could not normally occur as data A loop that process data until the sentinel value is entered has the form Dr. Chow-Sing LinRepetition and Loop Statement - CH Get a line of data. 2. while the sentinel value has not been encountered 3. Process the data line. 4. Get another line of data.

Sentinel-Controlled Loops (Cont.) Using a while statement Dr. Chow-Sing LinRepetition and Loop Statement - CH 533

Sentinel-Controlled Loops (Cont.) Using a for statement printf(”Eneter first score (or %d to quit)> “, SENTINEL); for (scanf(“%d”, &score); score != SENTINEL; scanf(“%d”, &score)) { sum += score ; printf(“Enter next score (%d to quit)> “, SENTINEL); } Dr. Chow-Sing LinRepetition and Loop Statement - CH 534

Endfile-Controlled Loops Design a repetition statement very similar to the sentinel controlled loop Use the state value returned – By the scanning function to control repetition The pseudo code for an endfile-controlled loop Dr. Chow-Sing LinRepetition and Loop Statement - CH Get the first data value and save input status 2. while input status does not indicate that end of file has been reached 3. Process the data value 4. Get next data value and save input status

Endfile-Controlled Loops (Cont.) scanf() returns the number of items of the argument list successfully filled. What about the input is 7a? – Infinite loop on faculty data !! Correction while (input_status ==1) { …….. } if (input_status ==EOF) printf(“the sum is” %d”, sum); else { scanf(inp, “%c”, &bad_char); printf(“Error input: %c”, bad_char); } Dr. Chow-Sing LinRepetition and Loop Statement - CH 536

Nested Loops Nested loops consist of an outer loop with one or more inner loops Each time the outer loop is repeated – The inner loops are reentered – Loop control expressions are reevaluated Dr. Chow-Sing LinRepetition and Loop Statement - CH 537

Nested Loops (Cont.) Example 5.8 (Page 290) Dr. Chow-Sing LinRepetition and Loop Statement - CH 538

Nested Loops (Cont.) Example 5.8 (Page 290) Exercises : What is displayed by the following program segments, assuming m = 3 and n = 5 ? Dr. Chow-Sing LinRepetition and Loop Statement - CH 539 for (i = 1; i <= n; ++i) { for (j = 0; j < i; ++j) { printf(“*”); } printf(“\n”); } * ** *** **** ***** output

Nested Loops (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 540 for (i = n; i > 0; --i) { for (j = m; j > 0; --j) { printf(“*”); } printf(“\n”); } *** output Page 292: programming 1 and 2.

The do-while Statement and Flag-Controlled Loops Both the for statement and the while statement evaluate a loop repetition condition before the first execution of the loop body We write the pseudo code for an input validation loop as follow : – 1. Get a data value – 2. If data value isn’t in the acceptable range Go back to step 1 Dr. Chow-Sing LinRepetition and Loop Statement - CH 541

The do-while Statement and Flag-Controlled Loops (Cont.) SYNTAX Dr. Chow-Sing LinRepetition and Loop Statement - CH 542 do statement while (loop repetition condition); /* Find first even number input */ do status = scanf(“%d”, &num); while (status > 0 && (num % 2) != 0); Example

Flag-controlled Loops Flag – A type int variable (as boolean) – Represent whether or not a certain event has occurred A flag has one of two values – 1 (true) – 0 (false) Example 5.10 (Page 294) Dr. Chow-Sing LinRepetition and Loop Statement - CH 543

Dr. Chow-Sing LinRepetition and Loop Statement - CH 544

Testing get_int(10,20) Enter an integer in the range from 10 to 20 Invalid character Skipping rest of line. Enter an integer in the range from 10 to 20 inclusive> 2o Number 2 is not in range. Enter an integer in the range from 10 to 20 inclusive> 20 Dr. Chow-Sing LinRepetition and Loop Statement - CH 545

Iterative Approximations Find roots Dr. Chow-Sing LinRepetition and Loop Statement - CH 546

Change of Sign Implies an Odd Number of Roots Dr. Chow-Sing LinRepetition and Loop Statement - CH 547

Three Possibilities That Arise When the Interval [X left, X right ] Is Bisected Dr. Chow-Sing LinRepetition and Loop Statement - CH 548

Figure 5.19 Finding a Function Root using Bisection Method Dr. Chow-Sing LinRepetition and Loop Statement - CH 549

Dr. Chow-Sing LinRepetition and Loop Statement - CH 550

Dr. Chow-Sing LinRepetition and Loop Statement - CH 551

Dr. Chow-Sing LinRepetition and Loop Statement - CH 552

Figure 5.20 Sample Run of Bisection Program with Trace Code Included 1-53

Dr. Chow-Sing LinRepetition and Loop Statement - CH 554

Figure 5.23 Program to draw a moving ball Dr. Chow-Sing LinRepetition and Loop Statement - CH 555

Dr. Chow-Sing LinRepetition and Loop Statement - CH 556

How to Debug and Test Program Using debugger – Existing in most popular IDE. (visual studio and Eclipse) Without debugger – insert printf() to print system status whenever is necessary – Page. 294 Off-by-one loop errors Dr. Chow-Sing LinRepetition and Loop Statement - CH 557

Common Programming Errors for (i=1; i<10; i++) ; { ….. } while( x>xbig) x-=2; ++xbig; // end of while Dr. Chow-Sing LinRepetition and Loop Statement - CH 558 while (balance != 0.0) { }  while (balance < 0.0) { } do { ……. }while(again = 1) ;