3. control structures and data files structured programming –sequence structures –selection...
Post on 15-Jan-2016
281 views
TRANSCRIPT
3. Control structures and Data Files
• Structured Programming– Sequence structures– Selection structures– Repetition structures
• Pseudocode/Flowchart• Data Files• Linear Regression
3.1 Algorithm Development
Decomposition outline
1. Read the new time value2. Compute the corresponding velocity and
acceleration values3. Print the new velocity and acceleration
Top-Down Design
–Divide and Conquer–Stepwise refinement–Pseudocode/Flowchart–Evaluation of alternative solutions–Error conditions–Test data generation–Program workthrough
Flowchart Pseudocode
Main: read a,f_a;read c,f_c;read b;set f_b to f_a + (f_c-f_a)print f_b
Sequence Structure
b - ac - a
Read a,f_a
f_b=f_a + (f_c - f_a )
print f_b
start main
stop main
Read c,f_c
b - ac - a
Read b
Is|denominator| < 0.0001
?
rdeniminato
numerator fraction
print fraction
print “Denominator close to zero
no yes
Selection StructureIf |denominator| < 0.0001
print “Denominator close to zero”else
set fraction to numerator/denominatorprint fraction
Flowchart
Pseudocode
time = 0
Istime ≤ 10
?
Compute velocity
print velocity
Increment time by 1
yes
no
Repetition Structure
Flowchart Pseudocode
set time to 0while time ≤ 10
compute velocityprint velocityincrement time by 1
Relational operators
3.2 Condition Expressions
Conditions
a < bx + y >= 10.5fabs(denominator) < 0.001
d =b > c;If (d)
cnt ++
Logical operatorsand &&or ||not !
b = 3;c = 5;! ( b == c || b == 5.5 )
b = 3;c = !b;printf(“ b=%i c=%i “, b, c);
• if statement
• if/else statement
3.3 Selection Statement
If (a<50){
++ count;sum += a;
}
If (a<50){
++ count;sum += a;if (b>a)
b = 0;}
If ( fabs(denominator) < 0.0001 )printf(“Denominator close to zero”);
else{
x = numerator / denominator;printf(“x= %f \n”,x);
}
• Indentation
if ( x > y )if ( y < z )
k ++;else
m ++;else
j++;
if ( x > y )if ( y < z )
k ++;else
m ++;
if ( x > y )if ( y < z )
k ++;else
j++;
?
if ( a < b );
elsecount++;
if ( a >= b )count++;
else;
float a;if ( a == 10.5) ( fabs( a-10.5 ) < 10e-5)
printf (“ a = %f”,a);
• Conditional Operator
If ( a < b )count ++;
elsec = a + b;
a < b ? count ++ : (c= a + b) ;
c = a < b ? a : b ;c = a < b ? count++ : (c = a + b);
a = 3.0 ;b = 4.0 ;count = 0 ;
ccount
• Switch statement
If ( code == 10 )printf(“Too hot - turn equipment off \n”);
else{
If ( code == 11 )printf(“Caution - recheck in 5 minutes \n”);else{
If ( code == 13 )printf(“Turn on circulation fan \n”);
elseprintf(“Normal mode of operation \n”);
}}
• Switch statement(cont.)switch( code ){case 10 :
printf(“Too hot - turn equipment off \n”);break;
case 11 :printf(“Caution - recheck in 5 minutes \n”);break;
case 13 :printf(“Turn on circulation fan \n”);break;
default :printf(“Normal mode of operation \n”);break;
}
3.4 Loop Structure
while ( condition ){
statements;}
do{
statements;} while ( condition );
For(exp_1 ; exp_2 ; exp_3){
statements;}
Deg
ree
to R
adia
ns
0
0.00
0000
1
00.
1745
33
20
0.34
9066
:
:
:
:
for ( k =1, j=5 ; k<=10 ; k++, j++){
sum_1 += k ;sum_2 += j ;
}
• break and continue statement
Sum = 0for ( k=1 ; k <=20 ; k ++ ){
scanf ( “ %lf” , &x ) ;if ( x > 10.0 )
break;sum + = x;
}printf ( “sum = &f \n “, sum);
continue ;
3.5 Problem Solving 3.5 Problem Solving Applied:Applied:
Weather BalloonsWeather Balloons
1. PROBLEM STATEMENT• Using the polynomials that represent the altitude and velocity for a
weather balloons, print a table using units of meters and meters/second. Also find the maximum altitude (or height) and its corresponding time.Assume that the following polynomial represents the altitude or height in meters during the first 48 hours following the launch of a weather balloon:
alt(t) = -0.12t4 + 12t3 -380t2 + 4100t + 220– where the units of t are hours.
• The corresponding polynomial model for the velocity in meters per hours of the weather balloon is as follows:
v(t) = -0.48t3 + 36t2 - 760t + 4100
2. INPUT/OUTPUT DESCRIPTION
• INPUT : Starting timeTime incrementEnding time
• OUTPUT : The table of altitude and velocity values
The Maximum altitude and its corresponding time
3. HAND EXAMPLE
• Assume that the starting time is 0 hours, the time increment is 1 hour, and the ending time is 5 hours. To obtain the correct units, we need to divide the velocity value in meters/hour by 3600 in order to get meters/second. Using our calculator, we can then compute the following values:
• We can also determine the maximum altitude for this table, which is 12,645.00 meters, it occurred at 5 hours
Time Altitude(m)Velocity(m/
s)
0 220.00 1.14
1 3,951.88 0.94
2 6,994.08 0.76
3 9,414.28 0.59
4 11,277.28 0.45
5 12,645.00 0.32
4. ALGORITHM DEVELOPMENT
First step : Decomposition outline– breaks the solution into a series of
sequential steps
Decomposition Outline
1.Get user input to specify times for the table.
2.Generate and print conversion table and find maximum height and corresponding time.
3.Print maximum height and corresponding time.
4. ALGORITHM DEVELOPMENT(Cont.)
Second step : Refinement in Pseudocode
main: read initial, increment, final values from keyboard set max_height to zero set max_time to zero print table heading set time to initial while time<=final
compute height and velocity print height and velocity if height>max_height
set max_height to height set max_time to time
add increment to time print max_time and max_height
CodingCoding/*---------------------------------------------------*/ /* Program chapter3_4 *//* *//* This program prints a table of height and */ /* velocity values for a weather balloon. */ #include <stdio.h> #include <stdlib.h> #include <math.h> main(){
/* Declare and initialize variables. */ double initial, increment, final, time, height, velocity, max_time=0, ma
x_height=0;/* Get user input. */ printf("Enter initial value for table (in hours) \n"); scanf("%lf",&initial); printf("Enter increment between lines (in hours) \n"); scanf("%lf",&increment); printf("Enter final value for table (in hours) \n"); scanf("%lf",&final); /* Print report heading. */ printf("\n\nWeather Balloon Information \n"); printf("Time Height Velocity \n"); printf("(hrs) (meters) (meters/s) \n");
Coding(Cont..)Coding(Cont..)/* Compute and print report information. */ for (time=initial; time<=final; time+=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; printf("%6.2f %8.2f %7.2f \n", time,height,velocity/3600);
if (height > max_height) {
max_height = height; max_time = time;
} } /* Print maximum height and corresponding time. */ printf("\nMaximum balloon height was %8.2f meters \n", max_height);
printf("and it occurred at %6.2f hours \n",max_time); /* Exit program. */ return EXIT_SUCCESS;
}
5. TESTINGIf we use the data from the hand example, we have the following interaction with the program:
Enter initial value for table (in hours) 0 Enter increment between lines (in hours) 1 Enter final value for table (in hours) 5
Weather Balloon Information Time Height Velocity (hrs) (meters) (meters/s) 0.00 220.00 1.14 1.00 3951.88 0.94 2.00 6994.08 0.76 3.00 9414.28 0.59 4.00 11277.28 0.45 5.00 12645.00 0.32
Maximum balloon height was 12645.00 meters and it occurred at 5.00 hours.
altitude and velocity of the balloon for a period of 48 hours
Balloon Altitude
Balloon Velocity
3.6 Data FilesFILE *sensor1;sensor1 = fopen ( “ sensor1.dat”, “r”);fscanf ( sensor1, “ %lf %lf”, &t, &motion);
FILE *balloon;balloon = fopen ( “ balloon.dat”, “w”);fprintf (balloon, “%f %f %f \n”,
time, height, velocity);
fclose (sensor1);fclose (balloon);
#define FILENAME “sensor1.dat” …….sensor1 = fopen (FILENAME, “r”);
Reading Data Files
file namedata typesorder of datathe size of data
number of recordstrailer signal(sentinel signal)end of file indicator
Input file : sensor1.dat
100.0 132.50.1 147.20.2 148.30.3 157.30.4 163.20.5 158.20.6 169.30.7 148.20.8 137.60.9 135.9
Output
Number of sensor readings: 10Average reading: 149.77Maximum reading: 169.30Minimum reading: 132.50
Input file : sensor2.dat
0.0 132.50.1 147.20.2 148.30.3 157.30.4 163.20.5 158.20.6 169.30.7 148.20.8 137.60.9 135.9-99 -99
Input file : sensor3.dat
0.0 132.50.1 147.20.2 148.30.3 157.30.4 163.20.5 158.20.6 169.30.7 148.20.8 137.60.9 135.9
Generating Data File
3.7 Numerical Technique: Linear Modeling
Linear Representation
Time(s) Temperature(˚F)
0 0
1 20
2 60
3 68
4 77
5 110
y = m x + b
Equations for the “best” linear fit in terms of least squares
Equations for the “best” linear fit in terms of least squares
3.8 Problem Solving 3.8 Problem Solving Applied:Applied:
Ozone MeasurementsOzone Measurements
Back GroundBack Ground• Satellite sensors can be used to measure many differ
ent pieces of information that help us understand more about the atmosphere, which is composed of a number of layers around the earth. Starting at the earth's surface, the layers are the troposphere, stratosphere, mesosphere, thermosphere and exosphere. Consider a problem in which we have collected set of data measuring the ozone mixing ratio in parts per million volume (ppmv). Over small regions, these data are nearly linear, and thus we can use a linear model to estimate the ozone at altitudes other than ones for which we have specific data.
Atmospheric layers around the earth
(대류권 )(성층권 )( 중간권 )
( 온도권 )(외기권 )
1. PROBLEM STATEMENT
Use the least-squares technique to determine a linear model for estimating the ozone mixing ratio at a specified altitude.
• INOUT : Data file zone1.dat• OUTPUT : Range of altitudes
Linear model for ozone mixing ratio
2. INPUT/OUTPUT DESCRIPTION
3. HAND EXAMPLE• Assume that the data consist of the following four data
points:
• Using the equations, we can now compute the values of m and b:
Altitude(km)
Ozone Mixing Ratio (ppmv)
20 3
24 4
26 5
28 6
m = 0.37b = -4.6
First step : Decomposition outline– breaks the solution into a series of sequential
steps
Decomposition Outline
1. Read data file values and compute corresponding sums and ranges.
2. Compute slope and y intercept. 3. Print range of altitude and linear model.
4. ALGORITHM DEVELOPMENT
Second step : Refinement in Pseudocode
main: set count to zero set sumx, sumy, sumxy, sumx2 to zero while not at end-of-file
read x,y increment count by 1 if count = 1
set first to x add x to sumx add y to sumy add x*x to sumx2 add x*y to sumxy
set last to x compute slope and y intersect print first, last, slope, y intersect
4. ALGORITHM DEVELOPMENT(Cont.)
*-----------------------------------------------------------*/ /* Program chapter3_9 *//* */ /* This program computes a linear model for a set */ /* of altitude and ozone mixing ratio values. */ #include <stdio.h> #include <stdlib.h> #define FILENAME "zone1.dat" main() {
/* Declare and initialize variables. */ int count=0; double x, y, first, last, sumx=0, sumy=0, sumx2=0, sumxy=0, denominator, m, b; FILE *zone1; /* Open input file. */ zone1 = fopen(FILENAME,"r"); /* While not at the end of the file, */ /* read and accumulate information. */ while ((fscanf(zone1,"%lf %lf",&x,&y)) == 2) {
++count; if (count == 1) first = x; sumx += x; sumy += y; sumx2 += x*x; sumxy += x*y;
} last = x;
Coding
Coding(Cont.)/* Compute slope and y-intercept. */ denominator = sumx*sumx - count*sumx2; m = (sumx*sumy - count*sumxy)/denominator; b = (sumx*sumxy - sumx2*sumy)/denominator; /* Print summary information. */ printf("Range of altitudes in km: \n"); printf("%.2f to %.2f \n\n",first,last); printf("Linear model: \n"); printf("ozone-mix-ratio = %.2f altitude + %.2f \n", m,b); /* Close file and exit program. */ fclose(zone1); return EXIT_SUCCESS;
} /*---------------------------------------------------*/
5. TESTING
• Using the data from the hand example as the contents of the data file zone1.dat, we get the following program output:
Range of altitude in km:
20.00 to 28.00
Linear model:
ozone-mix-ratio = 0.37 alitutde + -4.60