C++ For Engineers and Scientists

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 31

C++ for Engineers and Scientists

Chapter Five Repetition Structures

Types of Repetition Structures in C++


Statement Control while for do while Counted Testing Pre-test Conditional Pre-test Conditional Post-test

Pre-test and Post-test loops


x

Pre-test loops are entrance controlled loops.


x You

execute the loop body after evaluating the

test. x Loop body can be executed zero or more times.


x

Post-test loops are exit controlled loops.


x You

test the loop after executing the entire loop body. x Loop body can be executed one or more times.

The While Loop


Syntax of While Loop
bool expr true statements next stmt. false

while (boolean expr) statement; next statement; while (boolean expr) { statement 1; statement 2; } next statement;

Notes on semantics of While Loop


x x

x x x

All variables in the boolean expression must be initialized prior to the loop. At least one of the variables in the boolean expression must be assigned a new value inside the loop. In other words the boolean expression must change its value inside the loop. The boolean expression is tested prior to entering the loop and before each repetition of the loop body. The entire loop body is executed if the boolean expression is true. It is possible not to execute the loop body, this occurs when the boolean expression is initially false.

Example involving While Loop


x

Write a program to calculate the value of the nth Fibonacci number. The first and second Fibonacci numbers are 1; the third Fibonacci number is 2; and so forth where the next Fibonacci number is the sum of the two previous Fibonacci numbers.

void main() { int Fib, NumPrev, NumCurr, N; cin>>N; if (N <= 0) cout << "N = "<< N << "invalid value\n"; else { NumPrev = NumCurr = 1; // Initialization while ( (N -2) > 0) { // Calculate next Fibonacci number Fib = NumPrev + NumCurr; // Update for next iteration NumPrev = NumCurr; NumCurr = Fib; N--; } cout << "The desired number is: " << NumCurr <<endl; } }

Infinite Loops
x

An infinite loop is one in which the condition is initially satisfied, so the loop is entered, but the condition for exiting the loop is never met. Generally an infinite loop is caused by failing to modify a variable involved in the condition within the loop body. To break out of a malfunctioning program press ctrlbreak, on an DOS or Windows machine.

What Does This Loop Print?


int I = 1; while ( I < 6) cout << "Line number " << I << endl;
How should it be fixed to print the numbers between 1 and 5 inclusive in a column?

Interactive I/O and Looping


x

The sentinel or trailer technique uses a special endof data value to indicate the end of meaningful data. Using the while loop, we place an input statement before the loop to read the first value and an input statement at the bottom of the loop to read the next value. The loop condition tests that the value is not equal to the sentinel value.

An Example of Sentinel Input


x

Read a list of values and compute their average. The list consists of positive integers and is terminated with the value -99.

#include <iostream.h> int main ( ) { int number, sum, cnt; // Initialization cout << "Enter a list of integers terminated by -99"; cin >> number; // Priming read sum = 0; cnt = 0; // Loop to sum and count values while (number != -99) { sum += number; ++cnt; cin >> number; // Read next number } // Calculate and print average cout << "The average is " << sum/float(cnt); return 0; }

Counter-Controlled Loops
A counter controlled loop is a looping control structure in which a loop variable manages the repetition by counting. x The syntax for a counter controlled loop in C and C++ is:
x

for (init expr; boolean expr; increment expr) statement;


x

A loop body of more than one statement, must be enclosed in curly braces.

Comparison of For and While Loops


for (I=1; I<=10; I++)
cout << I <<endl;

I = 1; while (I <=10) { cout << I<<endl; I++; }

Comments On The for Loop


x

All three expressions that are part of the for loop are optional, the semicolons are not optional. If the boolean expression is omitted you have an infinite loop. Use the for loop when you know exactly how many times the loop body is to be executed, either as a specific value or as an expression.

All parts of the for loop are optional


x

x x

I = 0; for ( ; I < 5; I++) cout << I << endl; for (I=0; I < 5;) { I++; cout << I << endl; } for (I=0; I < 5; I++) ; for ( ; ; )

break And continue Statements With Loops


The break statement causes the immediate termination of the execution of the loop body and the continuation of execution with the first statement after the loop. x The continue statement cause the immediate termination of the execution of the loop body but not the exiting of the loop.
x

Another Example
x

Write a program which will input the starting mileage, and the number of times you fill the tank on a trip. The program will then read the mileage at each fill-up and the number of gallons put into the tank. It should then compute the mpg for that particular fill-up and the cumulative mpg for the trip up to that point. (See pg 253 problem 11 for
information on how to computer mpg and cumulative mpg)

Basic outline of problem


x x

Read initial mileage and number of fill-ups Initialize total gallons to zero, and last mileage to initial mileage For each fill-up x Read mileage, and gallons. x Compute mpg and print. x Update total gallons, compute and print cumulative mpg. x Update last mileage to mileage. Print final mpg for entire trip.

#include <iostream.h> int main () { int total_gal, // Running total of gallons for trip curr_gal, // Gallons for this fill-up start_mile, // Starting odometer reading curr_mile, // Odometer reading at fill-up last_mile, // Odometer reading at previous fill-up gas_stops, // Number of gas stops for trip I; // Loop index // Read starting mileage and number of gas stops cout << "Enter the starting mileage "; cin >> start_mile; cout << "Enter the number of gas stops for trip " cin >> gas_stops; // Initialization last_mile = start_mile; total_gal = 0;

for (I = 1; I <= gas_stops; I++) { //Read gas stop info cout << "Enter the current mileage and gallons "; cin >> curr_mile >> curr_gal; //Compute and print mpg cout << "mpg since last stop is: " << float(curr_mile-last_mile)/curr_gal << endl; //Update total_gal total_gal += curr_gal; //Compute cumulative mpg cout << "cumulative mpg is: " << float(curr_mile-start_mile)/total_gal << endl; } // Print trip mgp cout << "Trip mpg is: " <<float(curr_mile-start_mile)/total_gal << endl; return 0; }

Now modify the program to error check the input data


x x

Check that starting mileage is greater than or equal to 0. x Print error and stop execution of program by returning 1. Check that gas stops is greater than or equal to zero. x Print error message. Check that each current mileage is greater than last mileage. x Print error message. Don't calculate mpg or cumulative mpg. Check that each current gallons is greater than 0. x Print error message. Don't calculate mpg or cumulative mpg. Check that trip mpg is not calculated if total gallons is 0. x Print error message. Don't calculate trip mpg.

#include <iostream.h> int main () { int total_gal, // Running total of gallons for trip curr_gal, // Gallons for this fill-up start_mile, // Starting odometer reading curr_mile, // Odometer reading at fill-up last_mile, // Odometer reading at previous fill-up gas_stops, // Number of gas stops for trip I; // Loop index // Read starting mileage and number of gas stops cout << "Enter the starting mileage "; cin >> start_mile; if (start_mile < 0) { cout << "Starting mileage less than 0, program abort."; return 1; } cout << "Enter the number of gas stops for trip " cin >> gas_stops; if (gas_stop <= 0) cout << "Number of gas stops is invalid.\n"; // Initialization last_mile = start_mile; total_gal = 0;

for (I = 1; I <= gas_stops; I++) { //Read gas stop info cout << "Enter the current mileage and gallons "; cin >> curr_mile >> curr_gal; if (curr_gal <= 0) { cout << "Current number of gallons is invalid\n"; continue; } //Update total_gal total_gal += curr_gal; if (curr_mile < last_mile) { cout << "Current odometer reading is invalid\n"; continue; //Compute and print mpg cout << "mpg since last stop is: " << float(curr_mile-last_mile)/curr_gal << endl; //Compute cumulative mpg cout << "cumulative mpg is: " << float(curr_mile-start_mile)/total_gal << endl; }

// Print trip mpg if (total_gal == 0) cout << "Total gallons equals zero, trip mpg is: 0\n" else cout << "Trip mpg is: " <<float(curr_mile-start_mile)/total_gal << endl; return 0; }

Nesting of Loops
x

The statements in the loop body may be any C++ statement including another looping statement. When a for loop is entered from the top, the initialization occurs and then the boolean expressions are executed. When it is entered as a result of completing execution of the loop body the increment and then the boolean expressions are executed.

Nested For Loops


for ( I =1; I <= 5; I++) for (K = 1; K <= 3; K++) cout <<I <<, <<K<<endl; {next statement } OUTPUT: 1, 1 1, 2 1, 3 2, 1 2, 2 2, 3 3, 1 ... 5, 3 I=1 I = I+1 I<=5 next stmt. K=1 K = K+1 K<=3

cout <<I <<","<<K

Loop with Posttest


x

statements

Syntax to Do-While Loop do statement; while (bool expr); do { statement1; statement 2; } while (bool expr);

true

bool expr

false

Next statement

An example of the Do While Loop


int I = 1; do { cout << Line number << I << endl; I++; } while (I < 6);

Notes on semantics of Do While Loop


x

At least one of the variables in the boolean expression must be assigned a new value inside the loop. In other words the boolean expression must change value inside the loop. The boolean expression is tested at the end of the loop body after each execution of the loop body. The entire loop body is executed if the boolean expression is true. The loop body is always executed at least once.

Determining The Loop To Use


If the statements of the loop may not be executed at all, use a while loop. x If the statements of the loop must be executed at least once either loop may be used but the do-while loop is preferable.
x

You might also like