Control Structures ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne
Structured Programming • Algorithm Development • Conditional Expressions • Selection Statements • Loops 206_C3
Structured Programming • Sequence • Sequence of steps performed one after another • Selection • Condition evaluated as true or false • if true, one set of statements executed • if false, another set of statements executed • Repetition • Repeat (loop through) a set of steps • As long as a condition is true 206_C3
start main stop main print radius, area isradius < 0? yes no Flowchart Symbols read radius area = π*radius2 206_C3
Sequence start main read radius area = π*radius2 print radius, area stop main 206_C3
isradius < 0? yes no Selection read radius area = π*radius2 print error print radius, area 206_C3
istime 10? no yes Repetition time = 0 compute velocity print velocity increment time 206_C3
Structured Programming • Alternative Solutions • Readable • Not necessarily shortest • Handle Error Conditions • Test for invalid data • Exit • Attempt to correct • Generate Test Data • Cover different ranges of values • Test boundary conditions 206_C3
Debugging • Compile Errors • Correct one or two obvious syntax errors • Recompile • Execution Errors • Include cout statements • Provide memory snapshot of key objects 206_C3
Relational Operators < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal Logical Operators && and || or ! not Conditional Expressions 206_C3
Operator Precedence 206_C3
a = 5.5 b = 1.5 k = 3 a + b >= 6.5 b - k > a a < 10 && a > 5 Examples 206_C3
if Statements if (condition) statement 1; if (condition) { statement 1; statement 2; ... statement n; } if/else Statement if (condition) statement 1; else statement 2; Selection Statements 206_C3
cin >> r; if (r < 0) cout << "error"; else { a = PI*r*r; cout << r << a; } isradius < 0? yes no Example read radius area = π*radius2 print error print radius, area 206_C3
Conditional Operator • if/else Statement if (a<b) count++; else c = a + b; • Conditional Statement a<b ? count++ : c = a + b; 206_C3
Practice • If dist is less than 50.0 and time is greater than 10.0, then increment time by 2; otherwise, increment time by 2.5. if (dist < 50.0 && time > 10.0) time+=2; else time+=2.5; 206_C3
Nested if/else Statements if (code == 10) cout << "Too hot - turn off." << endl; else if (code == 11) cout << "Caution - recheck in 5 min." << endl; else if (code == 13) cout << "Turn on fan." << endl; else cout << "Normal." << endl; 206_C3
Equivalent switch Statement switch (code) { case 10: cout << "Too hot - turn off." << endl; break; case 11: cout << "Caution - recheck in 5 min." << endl; break; case 13: cout << "Turn on fan." << endl; break; default: cout << "Normal." << endl; } 206_C3
Selection Statements • switch Statement switch (controlling expression) { case label_1: statements; case label_2: statements; ... default: statements; } 206_C3
If rank equals 1 or 2 then print "Low", else if rank equals 3 or 4 then print "High", otherwise print "Error". switch (rank) { case 1: case 2: cout << "Low" << endl; break; case 3: case 4: cout << "High" << endl; default: cout << "Error" << endl; } Practice 206_C3
Loop Structures • while Loop • Condition evaluated before statements are executed • If condition is false, statement block is skipped • If condition is true, statement block is executed and condition is evaluated again • Beware of infinite loops • <Ctrl> C while (condition) { statements; } 206_C3
Example /*-----------------------------------------------*/ /* Program chapter3_1 */ /* */ /* This program prints a degree-to-radian table */ /* using a while loop structure. */ #include <iostream> #include <iomanip> using namespace std; const double PI = 3.141593; 206_C3
Example int main() { // Declare and initialize objects. int degrees(0); double radians; // Set formats. cout << fixed << setprecision(6); 206_C3
Example // Print radians and degrees in a loop. cout << "Degrees to Radians" << endl; while (degrees <= 360) { radians = degrees*PI/180; cout << setw(6) << degrees << setw(10) << radians << endl; degrees += 30; } // Windows friendly exit system("PAUSE"); return 0; } 206_C3
Example 206_C3
Loop Structures • do/while Loop • Condition tested at end of loop • Loop always executed at least once do { statements } while (condition); 206_C3
Example // Print radians and degrees in a loop. cout << "Degrees to Radians" << endl; do { radians = degrees*PI/180; cout << setw(6) << degrees << setw(10) << radians << endl; degrees += 30; } while (degrees <= 360); 206_C3
Loop Structures • for Loop • Expression 1 initializes loop-control object • Expression 2 specifies condition to continue loop • Expression 3 specifies modification to loop-control object • After execution of statement block for (exp_1; exp_2; exp_3) { statements; } 206_C3
Example // Print radians and degrees in a loop. cout << "Degrees to Radians" << endl; for (int degrees=0; degrees<=360; degrees+=30) { radians = degrees*PI/180; cout << setw(6) << degrees << setw(10) << radians << endl; } 206_C3
Practice • What is the value of count after the nested for loops are executed? int count(0); for (int k=-1; k<4; k++) { for (int j=3; j>0; j--) { count++; } } 206_C3
Loop Structures • break Statement • Immediately exit from the loop • continue Statement • Skip remaining statements in the current iteration • Both useful when error conditions encountered 206_C3
Structured Input Loops • Counter-controlled Loop • Number of data values is known • Sentinel-controlled Loop • Special value indicates end of data • End-of-data Loop • Continues while new data is available • End of file function (Ch 4) 206_C3
Counter-controlled Loop // Prompt user for input. cout << "Enter the number of exam scores "; cin >> counter; cout << "Enter " << counter << " exam scores separated by whitespace "; // Input exam scores using counter-controlled loop. for(int i=1; i<=counter; i++) { cin >> exam_score; sum = sum + exam_score; } 206_C3
Counter-controlled Loop 206_C3
Sentinel-controlled Loop input data_value data_value!=sentinel False True input next data_value 206_C3
Sentinel-controlled Loop // Prompt user for input. cout << "Enter exam scores separated by whitespace." << endl; cout << "Enter a negative value to indicate the end of data. "; // Input exam scores using sentinel-controlled loop. cin >> exam_score; while(exam_score >= 0) { sum = sum + exam_score; count++; cin >> exam_score; } 206_C3
Sentinel-controlled Loop 206_C3
Problem Solving Applied • Weather Balloons • Problem Statement • Using polynomials that represent altitude and velocity, print a table using units of meters and meters per second. Find the maximum altitude and its time. • Input/Output Description Starting Time Table of Velocities and Altitude Time Increment Maximum Altitude and its Time Ending Time 206_C3
Problem Solving Applied • Hand Example • alt(t) = -0.12t4 + 12t3 - 380t2 + 4100t + 220 • v(t) = -0.48t3 + 36t2 - 760t + 4100 • Starting Time • t = 0 hours • Ending Time • t = 5 hours • Time Increment • 1 hour 206_C3
Problem Solving Applied • Algorithm Development • Get user input to specify times for table • Generate and print conversion table • Find and print maximum height and corresponding time 206_C3
Problem Solving Applied • Algorithm Refinement • Read initial, increment, final values from keyboard • Set max_height and max_time to zero • Print table heading and set time to initial • While time is less than or equal to final • Compute height and velocity • Print height and velocity • If height is greater than max_height • Set new max_height and max_time • Add increment to time • Print max_time and max_height 206_C3
/*----------------------------------------------------*/ /* Program chapter3_7 */ /* */ /* This program prints a table of height and */ /* velocity values for a weather balloon. */ #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { // Declare and initialize objects. double initial, increment, final, time, height, velocity, max_time(0), max_height(0); int loops;
// Get user input. cout << "Enter initial value for table (in hours) \n"; cin >> initial; cout << "Enter increment between lines (in hours) \n"; cin >> increment; cout << "Enter final value for table (in hours) \n"; cin >> final; // Print report heading. cout << "\n\nWeather Balloon Information \n"; cout << "Time Height Velocity \n"; cout << "(hrs) (meters) (meters/s) \n"; // Set formats. cout << fixed << setprecision(2); // Compute and print report information. // Determine number of iterations required. // Use integer index to avoid rounding error. loops = (int)( (final - initial)/increment );
for (int count=0; count<=loops; count++) { time = initial + count*increment; height = -0.12*pow(time,4) + 12*pow(time,3) - 380*time*time + 4100*time + 220; velocity = -0.48*pow(time,3) + 36*time*time - 760*time + 4100; cout << setw(6) << time << setw(10) << height << setw(10) << velocity/3600 << endl; if (height > max_height) { max_height = height; max_time = time; } } // Print maximum height and corresponding time. cout << "\nMaximum balloon height was " << setw(8) << max_height << " meters \n"; cout << "and it occurred at " << setw(6) << max_time << " hours \n";
Testing 206_C3
Summary • Structured Programming • Algorithm Development • Conditional Expressions • Selection Statements • Loops • Problem Solving Applied • End of Chapter Summary • C++ Statements • Style Notes • Debugging Notes 206_C3