C++ For Engineers and Scientists
C++ For Engineers and Scientists
C++ For Engineers and Scientists
test the loop after executing the entire loop body. x Loop body can be executed one or more times.
while (boolean expr) statement; next statement; while (boolean expr) { statement 1; statement 2; } next statement;
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.
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.
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.
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
A loop body of more than one statement, must be enclosed in curly braces.
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.
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 ( ; ; )
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)
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; }
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.
statements
Syntax to Do-While Loop do statement; while (bool expr); do { statement1; statement 2; } while (bool expr);
true
bool expr
false
Next statement
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.