Control Structures
Download
Report
Transcript Control Structures
Control Structures
ELEC 206
Computer Applications for
Electrical Engineers
Dr. Ron Hayne
Structured Programming
Algorithm Development
Conditional Expressions
Selection Statements
Loops
206_C3
2
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
3
Flowchart Symbols
Operation
Symbol
Begin / End
start main
Input / Output
read radius
Computation
area = π*radius2
Comparison
is
radius < 0
?
no
206_C3
stop main
print radius, area
yes
4
Sequence
start main
read radius
area = π*radius2
print radius, area
stop main
206_C3
5
Selection
read radius
is
radius < 0
?
no
yes
area = π*radius2
print error
print radius, area
206_C3
6
Repetition
time = 0
is
time 10
?
yes
no
compute velocity
print velocity
increment time
206_C3
7
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
8
Debugging
Compile Errors
Correct one or two obvious syntax errors
Recompile
Execution Errors
Include cout statements
Provide memory snapshot of key objects
206_C3
9
Conditional Expressions
Relational Operators
<
<=
>
>=
==
!=
Logical Operators
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal
206_C3
&&
||
!
and
or
not
10
Operator Precedence
Precedence
Operation
1
2
3
4
( )
++ -- +
* / %
+ -
5
6
7
< <= >
== !=
&&
8
9
||
= +=
206_C3
-=
-
!
(type)
>=
*=
/=
%=
11
Examples
a = 5.5
b = 1.5
k=3
a + b >= 6.5
b - k > a
a < 10 && a > 5
206_C3
12
Selection Statements
if Statements
if/else Statement
if (condition)
statement 1;
if (condition)
statement 1;
else
statement 2;
if (condition)
{
statement 1;
statement 2;
...
statement n;
}
206_C3
13
Example
read radius
is
radius < 0
?
no
yes
area = π*radius2
print error
print radius, area
206_C3
cin >> r;
if (r < 0)
cout << "error";
else
{
a = PI*r*r;
cout << r << a;
}
14
Conditional Operator
if/else Statement
if (a<b)
count++;
else
c = a + b;
Conditional Statement
a<b ? count++ : c = a + b;
206_C3
15
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
16
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
17
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
18
Selection Statements
switch Statement
switch (controlling expression)
{
case label_1:
statements;
case label_2:
statements;
...
default:
statements;
}
206_C3
19
Practice
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;
}
206_C3
20
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
21
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
22
Example
int main()
{
// Declare and initialize objects.
int degrees(0);
double radians;
// Set formats.
cout << fixed << setprecision(6);
206_C3
23
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
24
Example
206_C3
25
Loop Structures
do/while Loop
Condition tested at end of loop
Loop always executed at least once
do
{
statements
} while (condition);
206_C3
26
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
27
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
28
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
29
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
30
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
31
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
32
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
33
Counter-controlled Loop
206_C3
34
Sentinel-controlled Loop
input data_value
data_value
!=sentinel
False
True
input next
data_value
206_C3
35
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
36
Sentinel-controlled Loop
206_C3
37
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
38
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
Time Altitude (m) Velocity (m/s)
0
1
2
3
220.00
3,951.88
6,994.08
9,414.28
1.14
0.94
0.76
0.59
4
5
11,277.28
12,645.00
0.45
0.32
206_C3
39
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
40
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
41
/*----------------------------------------------------*/
/* 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
45
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
47