22
CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied verbatim from ECE 103 material by prof. Phillip Wong @ PSU

CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

Embed Size (px)

Citation preview

Page 1: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

CS 161Introduction to Programming

and Problem Solving

Chapter 16Iterative Statements in C++

Herbert G. Mayer, PSUStatus 10/30/2014

Initial content copied verbatim fromECE 103 material by prof. Phillip Wong @ PSU

Page 2: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

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

Page 3: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

3

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

Page 4: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

4

Setup

expression

post-code

StatementsTRUE

FALSE

Typical loops require these operations:

• Setup

• Test expression evaluation

• Update

Update

pre-code

Exit loop

Stay in loop

Each single pass through a loop is called an iteration

Page 5: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

5

A loop consists of several parts: Setup

Before entering the loop, any values referenced by the test expression should be initialized.

Test expression evaluationAn expression is tested to see if it is true or false.

true : Repeat the body of the loop false : Exit the loop

BodyThe body contains the code that is to be repeated. It can be a single statement or a statement block.

UpdateWithin the loop, there should be a way to update the test expression so that it will fail eventually.

Page 6: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

6

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

Page 7: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

7

Loops in C++

General loop types: Conditional loops

Statements are repeated for as long as a test expression remains true.→ while, do-while

Counted loopsStatements are repeated a specified number of times.→ for

Page 8: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

8

while

pre-code;

while ( expression )Statement// ; included in statement

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-codeb) At the loop head, evaluate expressionc) If expression is true

Execute Statement Include user code back to Step (b)else Exit the loop and continue at Step (d)

d) Execute post-code

Page 9: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

9

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 <stdio.h>

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;

elsesum += num;

// not recommended style of if} //end while

 printf( "sum = %d\n", sum );

return 0;} //end main

Page 10: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

10

Example:/* Echo an input stream ( capitalized, 'S' replaced by '$’ ) */#include <stdio.h>#include <ctype.h>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( ’S’ == ch ) { // ‘S’ ch = ’$’;} //end ifprintf( "%c", ch );

} //end whileprintf( "\n” );return 0;

} //end main

My sister is funny!MY $I$TER I$ FUNNY!

Page 11: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

11

do-while

pre-code;

doStatement// ; included in 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-codeb) Enter the loop and execute Statementc) At end of loop, evaluate expressiond) If expression is true

Goto Step (b)else Exit the loop and goto Step (e)

e) Execute post-code

Page 12: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

12

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 <stdio.h>

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

Page 13: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

13

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 expressionexpr2 → test expressionexpr3 → update expression

a)Execute pre-codeb)At start of loop, evaluate expr1c)If expr2 is true Execute Statement Evaluate expr3 Goto Step (c)else Exit the loop and goto Step (d)d)Execute post-code

Page 14: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

14

Mapping between simple for and while loops:

for( expr1; expr2; expr3 ){

Statements;}

// only required:for( expr1; expr2; expr3 )

Statement;

expr1; /* Setup */

while( expr2 ) /* Test */{

Statements;

expr3; /* Update */}

Page 15: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

15

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!

Page 16: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

16

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

Page 17: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

17

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 / 180.0 );

prod = 1;for( a = 1; a <= 3; a++ )

prod = prod * a;

#1 : a → 1prod = 1 * 1 → 1

#2 : a → 2prod = 1 * 2 → 2

#3 : a → 3prod = 2 * 3 → 6

for( ch='A'; ch<='Z'; ch++ )printf( "%c", ch );

/* infinite loop */for( ;; )

printf( "Hello\n” );

Page 18: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

18

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 <stdio.h>

int main( void ){ // main

int k;

for( k = 0; k < 3; k++ )printf("%d\n", k);

// end forprintf( "%d\n", k ); /* Works

*/

return 0;} //end main

// C99 version#include <stdio.h>

int main( void ){ // main

// This is legal in C99for( int k = 0; k < 3; k++ )

printf("%d\n", k);// end for// Compiler fails on this kprintf( "%d\n", k );

return 0;} //end main

C99

Page 19: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

19

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, anddo-while loops

Page 20: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

20

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 1sum = 0;

while( TRUE ) {printf( "x? ” );scanf( "%d", &x );sum = sum + x;

if( sum > 1000 )break;

} //end while

Page 21: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

21

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

Page 22: CS 161 Introduction to Programming and Problem Solving Chapter 16 Iterative Statements in C++ Herbert G. Mayer, PSU Status 10/30/2014 Initial content copied

22

Example:#include <stdio.h>#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 < 10.0 || x > 95.0 ) /* Check for outside range */

continue;sum += x;if( sum > 250.0 ) /* Check if sum limit is reached */

break;} //end whileprintf( "sum = %f\n", sum );return 0;

} //end main