ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

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.
Chapter 5: Loops and Files.
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
Chapter 5: Control Structures II (Repetition)
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
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.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CMSC 104, Lecture 171 More Loops Topics l Counter-Controlled (Definite) Repetition l Event-Controlled (Indefinite) Repetition l for Loops l do-while Loops.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Repetition and Iteration ANSI-C. Repetition We need a control instruction to allows us to execute an statement or a set of statements as many times as.
ITERATIVE STATEMENTS. Definition Iterative statements (loops) allow a set of instruction to be executed or performed several until condition are met.
CMSC 104, Version 9/011 More Loops Topics Counter-Controlled (Definite) Repetition Event-Controlled (Indefinite) Repetition for Loops do-while Loops Choosing.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CS 161 Introduction to Programming and Problem Solving Chapter 18 Control Flow Through C++ Program Herbert G. Mayer, PSU Status 10/8/2014 Initial content.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
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.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
ECE 103 Engineering Programming Chapter 31 C Scopes Herbert G. Mayer, PSU CS Status 8/1/2015 Initial content copied verbatim from ECE 103 material developed.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CMSC 1041 More Loops ‘for’ loops and ‘do-while’ loops.
BY ILTAF MEHDI (MCS, MCSE, CCNA)1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI (MCS, MCSE, CCNA)2 Chapter No: 04 “Loops”
CS 161 Introduction to Programming and Problem Solving Chapter 17 Nested Loops Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
IT CS 200: R EPEATATION Lect. Napat Amphaiphan. T HE ABILITY TO DO THE SAME TASK AGAIN BY AGAIN UNTIL THE CONDITION IS MET LOOP 2.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 10P. 1Winter Quarter Repetition Structures Lecture 10.
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Week 4 – Repetition Structures / Loops
Quick Test What do you mean by pre-test and post-test loops in C?
Lecture 13 & 14.
Looping.
CS1100 Computational Engineering
CSC215 Lecture Control Flow.
Chapter 6: Repetition Statements
ECE 103 Engineering Programming Chapter 19 Nested Loops
ECE 103 Engineering Programming Chapter 12 More C Statements
ECE 103 Engineering Programming Chapter 20 Change in Flow of Control
More Loops Topics Counter-Controlled (Definite) Repetition
ECE 103 Engineering Programming Chapter 18 Iteration
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
CSC215 Lecture Control Flow.
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
Looping and Repetition
Presentation transcript:

ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed by Professor Phillip PSU ECE

Syllabus Basic Loops while do-while for break, continue Examples

2 Basic Loops Loops are another method of changing the execution sequence of a program, by iterating A loop is a section of code that is executed repeatedly as long as a condition remains true Once the expression becomes false (fails), the program ends the loop In C one can “hand-manufacture” loops via Goto Statements, viewed as sinfully evil; that is how a computer executes loops, by so-called “branch” or “jump” instructions

3 Setup expression post-codeStatements TRUE FALSE Typical loops require these operations: Setup Test expression evaluation Update pre-code Exit loop Stay in loop Each single pass through a loop is called an iteration

4 A loop consists of several parts:  Setup Before entering the loop, any values referenced by the test expression should be initialized.  Test expression evaluation An expression is tested to see if it is true or false. true: Repeat the body of the loop false: Exit the loop  Body The body contains the code that is to be repeated. It can be a single statement or a statement block.  Update Within the loop, there should be a way to update the test expression so that it will fail eventually.

5 Test expression must evaluate to either true (non-zero) or false (zero) Test expression is evaluated every iteration – either at the start or end of the loop The test is also called the termination condition An infinite loop occurs if the termination condition is never satisfied

6 Loop Statements in C General loop types:  Conditional loops Statements are repeated for as long as a test expression remains true. → while, do-while  Counted loops Statements are repeated a specified number of times. → for

7 while pre-code; while (expression) Statement; post-code; Use if the number of iterations is not known ahead of time Variables in expression must be initialized before entering the loop Loop body may be executed 0 or more times Note that the Statement may be a compound statement { } Execution Sequence a)Execute pre-code b)At start of loop, evaluate expression c)If expression is true Execute Statement Goto Step (b) else Exit the loop and goto Step (d) d)Execute post-code

8 Example: k = 0; while( k < 5 ) k = k + 1; // not recommended style of while k = 0; while( k < 5 ) { k = k + 1; printf( "k = %d\n", k ); } //end while num = 0; while( num < 5 ) { printf( "num = %d\n", num++ ); } //end while z = 5; while( z-- ) printf( "z = %d\n", z ); // not recommended style, no { } #include int main (void) { // main int num; /* Input from user */ int sum = 0; /* Running sum */ int Done = 0; /* Flag */ /* This adds up numbers > 0 */ while( !Done ) { printf( "Enter next number: ” ); scanf("%d", &num); if ( num < 1 ) Done = 1; else sum += num; // not recommended style of if } //end while printf( "sum = %d\n", sum ); return 0; } //end main

9 Example: // Echo an input stream ( capitalized, 'S' replaced by '$’ ) #include int main( void ) { // main int ch; /* Holds input character */ /* Read input stream until end-of-line is detected */ while( ( ch = getchar() ) != '\n' ) { ch = toupper( ch ); if( ch == 'S' ) ch = '$'; printf( "%c", ch ); } //end while printf( "\n” ); return 0; } //end main My sister is funny! MY $I$TER I$ FUNNY!

10 do-while pre-code; do Statement; while (expression); post-code; The do-while loop tests the expression at the end Hence will be done at least once! Note semicolon after ending parenthesis, as that is the end of the do- while statement Execution Sequence a)Execute pre-code b)Enter the loop and execute Statement c)At end of loop, evaluate expression d)If expression is true Goto Step (b) else Exit the loop and goto Step (e) e)Execute post-code

11 Example: k = 0; do k = k + 1; while( k < 5 ); k = 0; do { k = k + 1; printf( "k = %d\n", k ); } while( k < 5 ); #include int main( void ) { // main int num; /* Input from user */ int sum = 0; /* Running sum */ int Done = 0; /* Flag */ /* This adds up numbers > 0 */ do { printf( "Enter next number: ” ); scanf( "%d", &num ); if( num < 1 ) // not recommended! Done = 1; else sum += num; } while( !Done ); printf( "sum = %d\n", sum ); return 0; } //end main

12 for pre-code; for (expr1; expr2; expr3) Statement; post-code; Often used if the number of iterations is known ahead of time. Loop body may be executed zero or more times Execution Sequence expr1 → setup expression expr2 → test expression expr3 → update expression a)Execute pre-code b)At start of loop, evaluate expr1 c)If expr2 is true Execute Statement Evaluate expr3 Goto Step (c) else Exit the loop and goto Step (d) d)Execute post-code

13 Mapping between simple for and while loops: for( expr1; expr2; expr3 ) { Statements ; } expr1 ; /* Setup */ while( expr2 ) /* Test */ { Statements ; expr3 ; /* Update */ }

14 Example: for( k=0; k<=3; k++ )... → 4 iterations, values of k : 0, 1, 2, 3 for( t=1; t<11; t+=2 )... → 5 iterations, values of t : 1, 3, 5, 7, 9 for( x=1.0; x<=2.0; x+=0.5 )... → 3 iterations, values of x : 1.0, 1.5, 2.0 // careful “float” for( cnt = 2; cnt >= -1; cnt-- )... → 4 iterations, values of cnt : 2, 1, 0, -1 for( ;; ) → Infinite loop: expr2 is never false!

15 Be careful counting iterations, especially when starting at 0, or using < versus <= in expressions! Example: for( k=1; k<=5; k++ )... → 5 iterations, values of k : 1, 2, 3, 4, 5 for( k=1; k<5; k++ )... → 4 iterations, values of k : 1, 2, 3, 4 for( k=0; k<=5; k++ )... → 6 iterations, values of k : 0, 1, 2, 3, 4, 5 for( k=0; k<5; k++ )... → 5 iterations, values of k : 0, 1, 2, 3, 4

16 Example: for( n = 1; n < 5; n++ ) printf( "n = %d\n", n ); for( n = 1; n < 5; ++n ) printf( "n = %d\n", n ); for( n = 1; n < 5; ) printf( "n = %d\n", n++ ); s_idx = 2; e_idx = 4; for( n = s_idx; n <= e_idx; n++ ) { x = exp( n ); printf( "%d %f\n", n, x ); } //end for for( T = 10; T >= 0; T-- ) x = sin( T*pi / ); prod = 1; for( a = 1; a <= 3; a++ ) prod = prod * a; #1 : a → 1 prod = 1 * 1 → 1 #2 : a → 2 prod = 1 * 2 → 2 #3 : a → 3 prod = 2 * 3 → 6 for( ch='A'; ch<='Z'; ch++ ) printf( "%c", ch ); /* infinite loop */ for( ;; ) printf( "Hello\n” );

17 Variable Declarations in for Loops Variable declarations are allowed in the first expression of the for loop header. Typically used to declare the iteration variable Note: NOT in old versions of C! The scope of the variable extends only to the body of the loop /* C90 version */ #include int main( void ) { // main int k; for( k = 0; k < 3; k++ ) printf("%d\n", k); // end for printf( "%d\n", k ); /* Works */ return 0; } //end main // C99 version #include int main( void ) { // main // This is legal in C99 for( int k = 0; k < 3; k++ ) printf("%d\n", k); // end for // Compiler fails on this k printf( "%d\n", k ); return 0; } //end main C99

18 break Statement break causes an immediate exit from the loop that contains it; note: innermost loop! Once a break is encountered, execution goes to the first statement following the loop body break statements work with for, while, and do-while loops

19 Example: /* Use a state variable */ done = 0; /* State */ sum = 0; while( !done ) { printf( "x? ” ); scanf( "%d", &x ); sum = sum + x; if( sum > 1000 ) done = 1; } //end while /* Use a break statement */ #define TRUE 1 sum = 0; while( TRUE ) { printf( "x? ” ); scanf( "%d", &x ); sum = sum + x; if( sum > 1000 ) break; } //end while

20 continue Statement The continue statement restarts a loop Once a continue is encountered, execution proceeds to the start of the loop continue statements work with for, while, and do-while loops. If continue is used in a for statement, the setup expression is not executed again

21 Example: #include #define TRUE 1 int main (void) { // main float x; /* Input value */ float sum = 0.0; /* Accumulates partial sums */ while( TRUE ) { scanf( "%f\n", &x ); if( x 95.0 ) // Check for outside range continue; sum += x; if( sum > ) /* Check if sum limit is reached */ break; } //end while printf( "sum = %f\n", sum ); return 0; } //end main