+ All Categories
Home > Documents > Chapter 8 Repetition Statements

Chapter 8 Repetition Statements

Date post: 18-Jan-2016
Category:
Upload: will
View: 88 times
Download: 1 times
Share this document with a friend
Description:
Chapter 8 Repetition Statements. Spring 2014. Chapter 8 Repetition Statements. Introduction. Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or statements, that will be repeated. 8.1 General Repetition Concepts. - PowerPoint PPT Presentation
34
Chapter 8 Repetition Statements Spring 2014
Transcript
Page 1: Chapter 8  Repetition Statements

Chapter 8 Repetition Statements

Spring 2014

Page 2: Chapter 8  Repetition Statements

Chapter 8

Repetition Statements

Page 3: Chapter 8  Repetition Statements

Introduction

Iteration - process of looping or the repetition of one or more statements

Loop body - the statement, or statements, that will be repeated

Page 4: Chapter 8  Repetition Statements

8.1 General Repetition Concepts

Two different categories of loops• Pre-test: Test condition first - complete the

body of the loop if condition is true

• Post-test: Test condition after body has executed once - body will only be repeated if the condition is true

Page 5: Chapter 8  Repetition Statements

8.1 General Repetition Concepts

Start Loop Start Loop

EvaluateCondition

Body of Loop

Body of Loop

EvaluateCondition

End Loop End Loop

True

False

True

False

Pre-TestLoop

Post-TestLoop

Page 6: Chapter 8  Repetition Statements

8.1 General Repetition Concepts

Looping structures must have the following:• Variable with an initial value that controls

whether the body of the loop is executed (i.e., control variable)

• Conditional expression involving control variable

• Statement within the body where control variable is modified each time the body of the loop is executed

Page 7: Chapter 8  Repetition Statements

8.1 General Repetition Concepts

Infinite loop – a loop that continuously executes - the program or loop has to be terminated by the user or programmer• Usually an error situation

• Most common cause - failure to manipulate the control variable

• In Windows - pressing Ctrl + C causes program to stop execution

Page 8: Chapter 8  Repetition Statements

8.1 General Repetition Concepts

Nested loop - loop embedded in another loop

Almost any statement can be placed in loop body - including other loops or conditional statements

Once finished, flow transfer's to the next statement following the loop

Page 9: Chapter 8  Repetition Statements

8.1 General Repetition Concepts

Three loop structures

while loop:

while (<condition>) <action>

do while loop:

do <action> while <condition>;

for loop:for (<init-expr>; <condition>; <post-loop-expr>) <action>

Page 10: Chapter 8  Repetition Statements

8.2 The while Loop

Pre-test loopSyntax:

while ( <condition> )<action>

• Action, or body, will continue to execute while the condition remains true

• If the body needs to include multiple statements, surround them (action) with curly braces

Page 11: Chapter 8  Repetition Statements

8.2 The while Loop

Sometimes see a loop written as: while ( 1 ) { ... }

The numeric literal 1 is treated as a true condition and never changes – causing an infinite loop

Page 12: Chapter 8  Repetition Statements

8.2 The while Loop

while ( 1 ) { ... }

• Requires additional statement within the body of the loop to terminate it

• Although there are reasons to use this type of loop, it should only be used by experienced programmers and then only with due consideration

Page 13: Chapter 8  Repetition Statements

8.2 The while Loop

char again = '\0';int operand1 = 0, operand2 = 0;

cout << "\nDo you wish to multiply two numbers (y/n)? ";cin >> again; // Priming read

while ( again == 'y' || again == 'Y' ) // Notice no semicolon{ // Start of the loop body (action) cout << "Enter first number: "; cin >> operand1;

cout << "Enter second number: "; cin >> operand2;

cout << "Result: " << operand1 << " * " << operand2 << " = " << operand1 * operand2 << endl; // Don’t forget to change the control variable cout << "\nDo you wish to multiply two more numbers (y/n)? "; cin >> again; } // End of the loop body (action)cout << "The End" << endl;

Page 14: Chapter 8  Repetition Statements

8.2 The while Loop

Priming read - a prompt prior to encountering a loop• Ensures the control variable has a user

provided value before evaluating the condition

• Must be a corresponding prompt as the last statement in the body of the loop

Page 15: Chapter 8  Repetition Statements

8.3 The do-while Loop

Post-test loop (the body of the loop always executes at least once)

Syntax:do<action>

while ( <condition> );

If the body needs to include multiple statements, surround them with curly braces

Page 16: Chapter 8  Repetition Statements

8.3 The do-while Loop

char menu_choice; float number;cout << "Please enter a number: ";cin >> number;do{ cout << "\n1) Square the Number\n" << "2) Cube the Number\n" << "3) Exit\n\n" << "Please enter menu choice: " << endl; cin >> menu_choice; switch ( menu_choice ) { case '1': cout << number << " Squared = " << number * number << endl; break; case '2': cout << number << " Cubed = " << number * number * number << endl; break; case '3': cout << "Goodbye" << endl; break; default: cout << "Invalid menu option" << endl; } } while ( menu_choice != '3' ); // Notice the semicolon

Page 17: Chapter 8  Repetition Statements

8.4 The for Loop

Generally used when the specific number of iterations are known

Both while loops and for loops are pre-test loops - could be used interchangeable

Page 18: Chapter 8  Repetition Statements

8.4 The for Loop

Syntax:

for ( <init-expr> ;

<condition> ;

<post-loop-expr> )

<action>

Page 19: Chapter 8  Repetition Statements

8.4 The for Loop

for ( <init-expr> ;

<condition> ;

<post-loop-expr> )

<action>

Four sections:• Requires the two semicolons (;) and the action• Can include multiple statements separated by

commas placed within both the <init-expr> and <post-loop-expr> sections

Page 20: Chapter 8  Repetition Statements

8.4 The for Loop

Order in which the parts are evaluated or executed:1.<init-expr>2.<condition>3.<action> (if true condition)4.<post-loop-expr>5.<condition>

The <init-expr> section is only executed once

Page 21: Chapter 8  Repetition Statements

8.4 The for Loop

Variable(s) declared in <init-expr> section only visible within the body of the loop

Not all compilers adhere to this standard - but you should

Page 22: Chapter 8  Repetition Statements

8.4 The for Loop

Common errors students make - put a semicolon after the closing parenthesis• Although legal, semicolon terminates the loop

• In effect - takes the place of the body of the loop

• Often a difficult error to find

Page 23: Chapter 8  Repetition Statements

8.4 The for Loop

for ( int i = 0; i < 5; i++ ) cout << i << ' ';// Output0 1 2 3 4

Start for loop

Initialize control variable(i = 0)

Check conditionIs i < 5?

Execute body of loop (Display contents of i)

Terminate for loop

False

True

Manipulatecontrol variable

(i++)

Page 24: Chapter 8  Repetition Statements

8.4 The for Loop

// Example 1for ( int i = 0; i < 5; i++ ) // No semicolon cout << i << endl;

// Example 2// Notice the multiple expressionsfor ( int i = 0, j = 5; i < 5; i++, j-- ) cout << i << ' ' << j << endl;// Example Output// Ex. 1 // Ex. 2 0 0 5 1 1 4 2 2 3 3 3 2 4 4 1

Page 25: Chapter 8  Repetition Statements

8.4 The for loop

int sum = 0, value;for ( int i = 0; i < 5; i++ ) // No semicolon{ cout << "Enter value " << i + 1 << ": "; cin >> value;

sum += value;} cout << "The sum of the five values is: " << sum << endl;// Example OutputEnter value 1: 4Enter value 2: 7Enter value 3: 3Enter value 4: 12Enter value 5: 99The sum of the five values is: 125

Page 26: Chapter 8  Repetition Statements

8.4.1 Nested for Loops

for loops can be nested

• Used in many algorithms

• Important when using multi-dimensional arrays

Page 27: Chapter 8  Repetition Statements

8.4.1 Nested for Loops

for ( int row = 0; row < 5; row++ ){ for ( int col = 0; col < 5; col++ ) cout << col << ' ';

cout << endl;}// Example Output0 1 2 3 40 1 2 3 40 1 2 3 40 1 2 3 40 1 2 3 4

Start for loop

Initialize control variable(row = 0)

Check condition

Is row < 5?

Initialize control variable(col = 0)

Check condition

Is col < 5?

Execute body of inner loop

Display contents ofcol

Print newline

End for loop

True

True

FalseChange

control variablecol++

ChangeControl variable

row++

False

Page 28: Chapter 8  Repetition Statements

8.4.1 Nested for Loops

for ( int row = 0; row < 5; row++ ){ for ( int col = row; col < 5; col++ ) cout << col << ' ';

cout << endl;}// Example Output0 1 2 3 41 2 3 42 3 43 44

Page 29: Chapter 8  Repetition Statements

8.5 Breakpoints and Loops

Debugging loops:• Time consuming and annoying if necessary to

step through the loop

• Breakpoints add functionality to break or stop execution, based upon a condition or after a line of code has been encountered a certain number of times

Page 30: Chapter 8  Repetition Statements

8.5 Breakpoints and Loops

Right clicking on a breakpoint shows popup menu that allows setting breakpoint properties

Page 31: Chapter 8  Repetition Statements

8.5 Breakpoints and Loops

The Breakpoint Condition allows setting a condition that when true, stops the loop

Page 32: Chapter 8  Repetition Statements

8.5 Breakpoints and Loops

Can also stop execution after a breakpoint has been encountered a specific number of times

Page 33: Chapter 8  Repetition Statements

8.7 C – The DifferencesIllegal in C to declare variables in the

initialization section of a for loop

All variables in C must be declared at the beginning of a block, right after an opening curly brace

C99 specifications allow the C++ conventions for variable declarations

Page 34: Chapter 8  Repetition Statements

8.7 C – The Differences

#include <stdio.h>int main(){ //Legal in both C++ and C: int count; for ( count = 0; count < 5; count++ ) printf( "%d\n", count );

// Legal in C++ (and C99) but not in older C: // for ( int i = 0; i < 5; i++ ) // cout << i << endl;

return 0;}


Recommended