Title: Control Structures
1Control Structures
- ELEC 206
- Computer Applications for Electrical Engineers
- Dr. Ron Hayne
2Structured Programming
- Algorithm Development
- Conditional Expressions
- Selection Statements
- Loops
3Structured 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
4Flowchart Symbols
read radius
area pradius2
5Sequence
start main
read radius
area pradius2
print radius, area
stop main
6Selection
read radius
area pradius2
print error
print radius, area
7Repetition
time 0
compute velocity
print velocity
increment time
8Structured 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
9Debugging
- Compile Errors
- Correct one or two obvious syntax errors
- Recompile
- Execution Errors
- Include cout statements
- Provide memory snapshot of key objects
10Conditional Expressions
- Relational Operators
- lt less than
- lt less than or equal to
- gt greater than
- gt greater than or equal to
- equal to
- ! not equal
- Logical Operators
- and
- or
- ! not
11Operator Precedence
12Examples
- a b gt 6.5
- b - k gt a
- a lt 10 a gt 5
13Selection Statements
- if Statements
- if (condition)
- statement 1
- if (condition)
-
- statement 1
- statement 2
- ...
- statement n
- if/else Statement
- if (condition)
- statement 1
- else
- statement 2
14Example
- cin gtgt r
- if (r lt 0)
- cout ltlt "error"
- else
-
- a PIrr
- cout ltlt r ltlt a
-
read radius
area pradius2
print error
print radius, area
15Conditional Operator
- if/else Statement
- if (altb)
- count
- else
- c a b
- Conditional Statement
- altb ? count c a b
16Practice
- 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 lt 50.0 time gt 10.0)
- time2
- else
- time2.5
17Nested if/else Statements
- if (code 10)
- cout ltlt "Too hot - turn off." ltlt endl
- else
- if (code 11)
- cout ltlt "Caution - recheck in 5 min." ltlt
endl - else
- if (code 13)
- cout ltlt "Turn on fan." ltlt endl
- else
- cout ltlt "Normal." ltlt endl
18Equivalent switch Statement
- switch (code)
-
- case 10
- cout ltlt "Too hot - turn off." ltlt endl
- break
- case 11
- cout ltlt "Caution - recheck in 5 min." ltlt
endl - break
- case 13
- cout ltlt "Turn on fan." ltlt endl
- break
- default
- cout ltlt "Normal." ltlt endl
19Selection Statements
- switch Statement
- switch (controlling expression)
-
- case label_1
- statements
- case label_2
- statements
- ...
- default
- statements
-
20Practice
- 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 ltlt "Low" ltlt endl
- break
- case 3
- case 4
- cout ltlt "High" ltlt endl
- default
- cout ltlt "Error" ltlt endl
-
21Loop 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
- ltCtrlgt C
- while (condition)
-
- statements
-
22Example
- /-----------------------------------------------
/ - / Program chapter3_1
/ - /
/ - / This program prints a degree-to-radian table
/ - / using a while loop structure.
/ - include ltiostreamgt
- include ltiomanipgt
- using namespace std
- const double PI 3.141593
23Example
- int main()
-
- // Declare and initialize objects.
- int degrees(0)
- double radians
- // Set formats.
- cout ltlt fixed ltlt setprecision(6)
-
24Example
- // Print radians and degrees in a loop.
- cout ltlt "Degrees to Radians" ltlt endl
- while (degrees lt 360)
-
- radians degreesPI/180
- cout ltlt setw(6) ltlt degrees
- ltlt setw(10) ltlt radians ltlt endl
- degrees 30
-
- // Windows friendly exit
- system("PAUSE")
- return 0
-
25Example
26Loop Structures
- do/while Loop
- Condition tested at end of loop
- Loop always executed at least once
- do
-
- statements
- while (condition)
27Example
- // Print radians and degrees in a loop.
- cout ltlt "Degrees to Radians" ltlt endl
- do
-
- radians degreesPI/180
- cout ltlt setw(6) ltlt degrees
- ltlt setw(10) ltlt radians ltlt endl
- degrees 30
- while (degrees lt 360)
-
-
28Loop 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
29Example
- // Print radians and degrees in a loop.
- cout ltlt "Degrees to Radians" ltlt endl
- for (int degrees0 degreeslt360 degrees30)
-
- radians degreesPI/180
- cout ltlt setw(6) ltlt degrees
- ltlt setw(10) ltlt radians ltlt endl
-
-
30Practice
- What is the value of count after the nested for
loops are executed? - int count(0)
- for (int k-1 klt4 k)
-
- for (int j3 jgt0 j--)
-
- count
-
-
31Loop Structures
- break Statement
- Immediately exit from the loop
- continue Statement
- Skip remaining statements in the current
iteration - Both useful when error conditions encountered
32Structured 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)
33Counter-controlled Loop
- // Prompt user for input.
- cout ltlt "Enter the number of exam scores "
- cin gtgt counter
- cout ltlt "Enter " ltlt counter ltlt " exam scores
- separated by whitespace "
- // Input exam scores using counter-controlled
loop. - for(int i1 iltcounter i)
-
- cin gtgt exam_score
- sum sum exam_score
-
34Counter-controlled Loop
35Sentinel-controlled Loop
input data_value
data_value!sentinel
False
True
input next data_value
36Sentinel-controlled Loop
- // Prompt user for input.
- cout ltlt "Enter exam scores separated by
- whitespace." ltlt endl
- cout ltlt "Enter a negative value to indicate
the - end of data. "
- // Input exam scores using sentinel-controlled
loop. - cin gtgt exam_score
- while(exam_score gt 0)
-
- sum sum exam_score
- count
- cin gtgt exam_score
-
37Sentinel-controlled Loop
38Problem 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
39Problem 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
40Problem 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
41Problem 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
42/------------------------------------------------
----/ / Program chapter3_7
/ /
/ / This program prints a
table of height and / / velocity
values for a weather balloon.
/ include ltiostreamgt include
ltiomanipgt include ltcmathgt using namespace
std int main() // Declare and initialize
objects. double initial, increment, final,
time, height, velocity, max_time(0),
max_height(0) int loops
43 // Get user input. cout ltlt "Enter initial
value for table (in hours) \n" cin gtgt
initial cout ltlt "Enter increment between
lines (in hours) \n" cin gtgt increment
cout ltlt "Enter final value for table (in hours)
\n" cin gtgt final // Print report
heading. cout ltlt "\n\nWeather Balloon
Information \n" cout ltlt "Time Height
Velocity \n" cout ltlt "(hrs) (meters)
(meters/s) \n" // Set formats. cout ltlt
fixed ltlt setprecision(2) // Compute and
print report information. // Determine number
of iterations required. // Use integer index
to avoid rounding error. loops (int)( (final
- initial)/increment )
44 for (int count0 countltloops count)
time initial countincrement
height -0.12pow(time,4) 12pow(time,3)
- 380timetime 4100time 220
velocity -0.48pow(time,3) 36timetime
- 760time 4100 cout ltlt
setw(6) ltlt time ltlt setw(10) ltlt height
ltlt setw(10) ltlt velocity/3600 ltlt endl if
(height gt max_height) max_height
height max_time time
// Print maximum height and corresponding
time. cout ltlt "\nMaximum balloon height was "
ltlt setw(8) ltlt max_height ltlt " meters
\n" cout ltlt "and it occurred at " ltlt setw(6)
ltlt max_time ltlt " hours \n"
45Testing
46(No Transcript)
47Summary
- Structured Programming
- Algorithm Development
- Conditional Expressions
- Selection Statements
- Loops
- Problem Solving Applied
- End of Chapter Summary
- C Statements
- Style Notes
- Debugging Notes