REVIEW DID YOU THINK ABOUT THE SUBTLE ISSUES HERE The Example using the switch statement. PLAY COMPUTER in class show in a table the values of the variables for the given input!!!! char ch; int ecount=0, vowels=0, other=0; cin.get(ch); while(ch!= x ) switch(ch) case e : ecount++; case a : case i : case o : case u : vowels++; break; default: other++; //end switch cin.get(ch); //end while cout << ecount <<, << vowels <<, << other << endl; Class? First time Output for input of e x? U x? a x? Output for the following sequence e u z i x? NOTE: Each letter input is obtained by the cin.get(ch) with an enter key. What is the consequences of no break statement in a case.
REVIEW BE SURE TO DO Hand in HW CHAP3. Be sure to read and study the Summary section of each Chapter to understand what you should know with the exception of the section(s) I skip for now. HAND IN the Exam Practice 1-20 on pages 135-137. Note for the memory snapshot 14,15 questions. Show the value of variables after the statements have been executed and any output that might occur in the end
Outline chapter 4 control structures: REPETITION Objectives 1. Algorithm Development (FLOWCHARTS) for repetition 2. Repetition Structures while do/while for 3. Special use of C++ break and continue Statements 4. Study of text applied problems GPS Data & Weather Balloons
Text uses isspace( ) but does not define it isspace() int isspace ( int c ); Check if character is a white-space Checks whether c is a white-space character. Character Meaning ' ' space (SPC) '\t' horizontal tab (TAB) '\n' newline (LF) '\v' vertical tab (VT) '\f' feed (FF) '\r' carriage return (CR)
/* isspace example */ #include <stdio.h> // (header file) NEW NEEDED FOR putchar() #include <ctype.h> // NEW NEEDED FOR isspace() int main () char c; int i=0; char str[]="example sentence to test isspace\n"; while (str[i]) c=str[i]; if (isspace(c)) c='\n'; putchar (c); i++; return 0; Output! Example sentence to test isspace
The while Statement Syntax: while (boolean_expression) statement; while (boolean_expression) statement1; statement_n; Examples while (!isspace(ch)) cin.get(ch); //statement repeated until a // space character is read While LOOP while (x>y) //statement block executed //while x>0 ++cl; --x; // loop variable changes
Example sentence to test isspace Example: Computing Velocity over a Range of Time. Sequential structures are not well suited for computing the same quantities repeatedly. Flow charts are very useful Also to describe repetition. CLASS WRITE THE PROGRAM NOW FROM THIS CHART RUN IT AND HAND IN! Note: v=at a=1.8 m/s 2 Make a comment // FLOWCHART TRANSLATION
Motion with constant acceleration v = final velocity v 0 = initial velocity a= acceleration (the change in velocity per time) v = v 0 +at Also note that all objects fall at the same rate as discovered by Galileo a= gravity constant = 9.80 m/s an amazing fact!
/*****************************************************/ Program chapter4_1 variation now online! */ This program computes and prints a velocity for time */ table values in the range of: 0 <= time <= 10 */ #include<iostream> //required for cout #include<iomanip> // required for what????? using namespace std; int main() // Declare and initialize some constants const double V0(0.0); //initial velocity m/s const double A(2.537); //constant acceleration m/s*s double time, velocity; //print heading cout << "Time, s\t\tvelocity, m/s\n"; time = 0; while(time <= 10.0) velocity = A*time + V0; cout << setw(10) << time << "\t\t" << velocity << endl; ++time; return 0; RUN! THIS PROGRAM and hand in some of its output along with The next MODIFICATIONS.
MID TERM EXAM IN ONE WEEK!
Infinite Loops SOME CLASS WORK An infinite loop is one in which the loop condition is always true. RUN THE PREVIOUS PROGRAM BUT REMOVE OR comment out the ++ time What happens? Why do we run the program in a separate window? ANSWER THESE QUESTIONS ON YOUR PREVIOUS HAND IN BUT NOW DO THE NEXT MODIFICATIONS TO HAND IN IF NOT DONE IN CLASS
HAND IN PROJECT I bet in a bar $100 each that my Volks Wagon could get to 60 miles/hr Faster than cars owned by some folks I met at the bar. These folks who had the cars listed below, and they gave me the time for their cars to reach 60 miles an hour starting from a stop. Fortunately the guys and gals there were engineers and when I ran the previous program at an acceleration of 9.80 m/s 2 up to 4 sec of time at a Step of 0.1 sec so they could understand the consequences. I pointed out that 26.8224 m/s = 60 mi/hr HAND in a Modification of the last program and the key output data attached (not all!) as I specified and let me know which cars did my Volks Wagon beat! How did I do, did I make a lot of money? If so How much did I win or lose or both? Also answer the following. NOTE: My Volks Wagon has no engine. How did I do this? 2015 Porshe 918 spyder 2.21 sec 2015 Nissan GT-R 2.8 sec 2015 Chevrolet Corvette z06 2.95 sec 2015 Mercedes-Benz E63 Amg 3.2 sec 2015 Dodge Viper SRt-10 3.4 sec 2015 Dodge Vhallenger SRT hell.. 3.4 sec 1994 Jaguar XJ220 3.5 sec
IN CLASS PROJECT FOX HEAVEN an island off the coast of Costa Rica near Isla Sorna (REPORTS OF STRANGE CREATURES ON THIS ISLAND) Write a program to study the population of foxes ON Fox Heaven Island as the years go by with the following conditions You study the island and count the foxes at 20 with a lot of rabbits, namely 13,000 rabbits. Looks like plenty of rabbits to keep this island going for a long time. So in your study you find information About the fox and rabbit reproduction and build this program to predict the future for the island. As follows: If every thing is ok, ie a GOOD YEAR foxes can survive by eating 208 rabbits for the year That means that a good year is if the total number of rabbits is greater than the number of present foxes times the 208 rabbits, if the present number of rabbits falls below the good year then it s a BAD YEAR AND AND FOXES WOULD NEED TO EAT ONLY 104 RABBITS TO JUST SURVIVE very skinny. In a good year the rabbit population goes up by 50% times the previous years value. And the foxes population increases 20% of the previous years value but if year is bad (#of rabbits < # foxes *208) ie not enough rabbits to fully satisfy the foxes and keep them healthy so they go on A lean diet of only eating 104 rabbits a year as noted above. The fox population grow now at only 10% and the rabbits increase by 50% (they are still healty) their population as rabbit normally do! These rates are a combination of births and deaths. 1. Write a program with year 1 starting numbers of foxes and rabbits as above. Have it calculate the first good year And see how many rabbits and foxes there are then check to see if it s a good or bad year and use the rates above. Output the year, the fox population, rabbit population in nice labeled table. Run for 15 years. Can FOX HEAVEN sustain itself, if the rabbit population drops to 0 or less then the foxes all die (if this happens your program should set the number Of foxes to zero in such a bad year and thus all on the island die. What year(s) did the island turn bad? What year does it die? 2. Take into account that the island has been discovered by hunters who hunt rabbits And foxes in a good year. The hunters kill 5% of the rabbits and 10% of the foxes. Rerun the program for as many years you need to see if the island Survives, flourishes or dies. If it goes bad what year(s)? And what year does it die if it does? Did the hunters make the situation on the island worse or better? Explain??
Avoiding Bugs When programming longer programs, it is not uncommon to have a large number of error messages from the compiler. A single error often causes several errors as the compiler gets confused over what follows an error. Start correcting errors from the top of the error list, NOT the bottom. Recompile your program frequently, limiting the places where errors may occur. Use endl in debugging output statements to be sure what you send is actually seen on screen.
start r in while() nest F r>100 T h F F r==0 r>0&&r<50 in T T WHILE() IS LIKE A NEST WITH STATEMENTS AND IF ELSE, etc INSIDE IT out out h, r, A sh, in r end
The do-while Statement Syntax: do statement; while (boolean_expression); do statement1; statement_n; while (boolean_expression); Examples do cin.get(ch); //statement repeated until an while (ch!= \n ) // newline character is read Focus on this do //statement block executed (AT LEAST ONCE v = a*t + v0; cout << t << << v << endl; t += 0.5; (NOTE LOOP VARIBLE MUST CHANGE) while (t<10); //while t< 10
/* Program chapter4_3 */ /* This program prints a degree-to-radian table */ /* using a do-while loop structure. */ #include<iostream> //Required for cout #include<iomanip> //Required for setw() using namespace std; const double PI = 3.141593; int main() // Declare and initialize objects. int degrees(0); double radians; // Set formats. cout.setf(ios::fixed); cout.precision(6); // Print degrees and radians in a loop. cout << "Degrees to Radians \n"; do radians = degrees*pi/180; cout << setw(6) << degrees << setw(10) << radians << endl; degrees += 10; while (degrees <= 360); // Exit program. return 0; Degrees to Radians 0 0.000000 10 0.174533 20 0.349066 30 0.523599 40 0.698132 50 0.872665 HAND in PROGRAM and output Run this program to 180 degrees, source IS on line Has an error. ANSWER! What is so special about the 180 degree line?
HW more do-while fun. RUN prog 4_1 AGAIN 1. MODIFY WITH A do-while check output is the same 2 MODIFY THAT user inputs initial velocity, constant acceleration, initial time and final time. Run and hand in this last modification with part 1 done with some output.
FOR LOOP The for Statement note flowchart symbol a full control on loop -very useful in scientific programs. The figure is called?
The for Statement Syntax: for (initialization_stmt; boolean_condition; modification_stmt) statement(s); Examples int sum=0; NOTE int i; for (int i = 1; i <= 10; i++) can also do as sum += i; usual and start cout << sum << endl; for(i=1. int sum=0; for (int i = 1; i < 11; ++i) sum += i; cout << sum << endl;
For loop possibilities and counting! Study page 149-150 How does these loops execute? for (int k=1;k<=10; ++k) statements; or n-=2 for (n=20; n>0; n=n-2;) statements How many time does this one execute? This is a a block for (int k=5; k< =83; k+=4) statements Secret for counting number floor ((Final Initial)/increment + 1) Later we apply for loops to arrays. 1D chap 7, 2D chap 8 E.g. 1 D array members could be vector components or list of data values for graphing! double s[6] = 1,4,7,4.9,5.1,20.45 so s[3]=7 s[6]=? s[?]=20.45 Class? like a vector components but here 6 values rather than 3. for (int i=0; i<6; ++i) cout << s[i] << ; CLASS OUTPUT? cout << endl;
Matrices as 2 D arrays! How do you solve the following ( the long way and short way)? 2x -8y =9 3x +6y =4 x=? y=? Using rows and columns of numbers we create matrices and evaluate them By the determinate rules. 9-8 4 6 54 - -32 86 8-27 -19 x= ---------- = ----------- = ------ =2.389 y = ------- = ----- = -0.528 2-8 12 - -24 36 36 36 3 6 check first equation 2 *2.389 8* (-0.528) = 9.002 We consider an entity that keeps track of values in rows and columns an array! So we can create a 2 Dimensional array from the above equations as 2-8 9 or two rows and three columns each position can be referred to the 3 6 4 by what row number and what column number the value is in in computers the first row is the 0 th row, as is the first columns the 0 th column. (math uses 1 in that case). So the the member at 0, 2 = 9 in this case, 1,2 =4 so 0,1 =? 1,0 =?
More Taste of 2D array with for loops! NESTED FOR LOOP. VERY IMPORTANT FOR ARRAY (MATRICES) HOW MANY TIMES DOES EACH LOOP EXECUTE & output =? For (int k=0; k<3; ++k) for (int j=0; j<2; ++j) ++ count cout <<k<< <<j<<count<<endl; CHECK OUT 1 D ARRAYS AND 2 D ARRAYS IN THE BEGINNINGS OF CHAP 7 AND CHAP 8 Welcome to Matrices: show output for the following, now in class! 2 D array ill. Int ving[3] [3] For (int k=0; k<3; ++k) for (int j=0; j<3; ++j) ving[k] [j]=k+j; cout <<ving[k] [j]<< <<; cout << endl;
/* Program chapter4_4 for loop (while loop would do the same!*/ /* */ /* This program prints a degree-to-radian table */ /* using a for loop structure. */ #include<iostream> // Required for setw() #include<iomanip> // Required for cout using namespace std; const double PI = 3.141593; int main() // Declare the objects. double radians; // Set formats. cout.setf(ios::fixed); cout.precision(6); // Print degrees and radians in a loop. cout << "Degrees to Radians \n"; for (int degrees = 0; degrees <= 360; degrees += 10) radians = degrees*pi / 180; If we wanted to step by 0.1 degrees would This program be ok.? How would you modify to handle steps of 0.1? cout << setw(6) << degrees << setw(10) << radians << endl; // Exit program. return 0; /*-----------------------------------------------------------*/
HW hand in answers to practice page 152 problems 1 to 6 MAJOR PROGRAMMING PROBLEM A STUDY of THE GLOBAL POSTIONING SYSTEM (GPS) It all started with Celestial Navigation. TYPICALLY A LOCATION CAN BE FOUND AT THE INTERSECTION OF THREE CIRCLES ON a flat map of the EARTH SINCE IF YOU KNOW THE DISTANCE(range) TO THREE REFERENCE POINTS AND CAN DRAW CIRCLES of proper size ON THE EARTH the Intersection of three such circles is our unique position. The three references on earth are where the star, or moon or Sun is directly over known As the sub point. Illustrated below are two sub points and known circular sizes Determined by a sextant instrument. Where is the possible location(s) of the observer In this case? Why is a third circle needed?
GPS consideration: Since satellites positioning is a three dimensional picture not a flat map as before we need the intersection of objects but spheres in 3D to find our position. The radius of a sphere is the range to the satellite and the minimum needed is 4 of them. A radio signal carrying data moving at the speed of light is broadcast to the satellite and rapidly there is received data. If you know the Time you sent the broadcast, T b and the time you received the response T r, you now know how much the round trip time called the TRANSIT TIME by taking the difference of the two times. T r -T b and since Rate x time =distance we define the range to the satellite (called the pseudorange,p) as P= (T r -T b ) C with C the speed of the radio wave which is the speed of light! Our problem to study is a part of the GPS solution (not all) as follows.
Problem Solving Applied: GPS Data
Problem Solving Applied: GPS Data
Problem Solving Applied: GPS Data
#include<iostream> //Required for cout prog 4_5! #include<cfloat> //required for DBL_MAX using namespace std; int main() //Declare and initialize objects const double C(299792458.0); //meters per second const int NUMBER_OF_SATELLITES(4); int satid, minid; double ttime, prange, minprange(dbl_max); cout << "Enter id and transit time for " //Prompt user for input << NUMBER_OF_SATELLITES << " satellites:\n" << "Use whitespace to separate the values(ie: 25 0.00567)\n" << endl; for(int i=1; i<=number_of_satellites; ++i) cin >> satid >> ttime; prange = ttime*c; if(prange < minprange) //Check for closest satellite minprange = prange; minid = satid; cout << "Satellite " << satid << " has a pseudorange of " << prange << " m\n" << endl; //Output ID of closest satellite cout << "\nsatellite " << minid << " is closest to GPS receiver." << endl; return 0; FINDING MIN AND MAX VALUES VERY IMPORANT PROCESS NOTE TECHNIQUE
HAND IN PROG Run the hand example first to be sure the code Is doing the right calculations. Then DO THE THREE MODIFICATIONS ON PAGE 157 OF THE SATELLITE GPS FOUND ONLINE AS PROG 4_5
REMINDER ALWAYS ON YOUR OWN BE SURE TO DO THE PRACTICE EXERCISE IN THE SECTIONS OF THE TEXT WE COVER IN CLASS. EVEN IF I DO NOT ASK FOR THEM, I EXPECT YOU TO HAVE DONE THEM! ALSO PLEASE LET ME KNOW IF YOU FIND ERRORS IN THE TEXT AS YOU READ IF I MISS THEM. ALL WORKS WHETHER POWER POINTS OR TEXTS DO HAVE SUCH SINCE THE AUTHOR GETS BLIND TO THEIR MISTAKES.. KEEP THIS IN MIND WHEN YOU HAVE TO WRITE ENGINEERING REPORTS! (EXTRA CREDIT FOR EACH ERROR FOUND IN THE TEXT!).
REMINDER EFFICENT CODING COUNTS! The next two illustrations show how to efficiently make Selections in the logic of your programs. It also demonstrates how not to do it and though the poor style was Tolerated to now, it no longer will be acceptable programming. Keep the latter in mind. Not sure, ask the professor! In each illustration Int code; cin >> code;
If (code=10) cout << Warning Too hot, turn the system off << endl; Else if (code= 11) cout << Warning check temperature every 5 minutes << endl; else if (code =13) cout << Warning, better turn on the circulating fan << endl; else if (code=16) cout << Emergency, Abandon the building explosion imminent << endl; else cout << Normal operating range, no problems << endl; NOTE ONCE ANY CONDITION IS TRUE THE PROGRAM MOVES ON THIS IS EFFICIENT CODING. THE SYSTEM DOES NOT HAVE TO TEST ALL, ALWAYS
THE FOLLOWING WILL HAVE THE SAME BASIC LOGIC BUT IS VERY BAD PROGRAMMING! WHY? Such coding though tolerated is no longer acceptable! If (code=10) cout << Warning Too hot, turn the system off << endl; if (code= 11) cout << Warning check temperature every 5 minutes << endl; if (code =13) cout << Warning, better turn on the circulating fan << endl; if (code=16) cout << Emergency, Abandon the building explosion imminent << endl; else cout << Normal operating range, no problems << endl;
The break Statement break; terminates loop ANY LOOP IN THIS CHAPTER! execution continues with the first statement following the loop Example: What is the output? for (int i=0; i<=10; ++i) if(i%2) break; cout << i << endl;
The continue Statement continue; forces next iteration of the loop, skipping any remaining statements in the loop Example: What is the output? for (int i=0; i<=10; ++i) if(i%2) continue; cout << i << endl;
ILLUSTRATION OF BREAK AND CONTINUE sum =0; for (int i=1; i<=20; ++i) cin >>x; if(x>10) break; What is sum for if we want inputs sum = sum + x; 5,7,8,12,9,11 cout <<sum<< endl; sum =0; for (int i=1; i<=20; ++i) cin >>x; if(x>10) continue; What is sum for if we want inputs sum = sum + x; 5,7,8,12,9,11 cout <<sum<< endl;
Structuring Input Loops Repetition is useful when inputting data from standard input or from a file. Common repetition structures: counter-controlled we are Counting! sentinel-controlled - special value! end-of-data controlled -
Counter-Controlled Loops May be used for reading input data if the number of data values is known before the data are entered.
COUNTER CONTROL /* This programs finds the average of a set of exam scores. */ #include<iostream>//required for cin, cout using namespace std; int main() double exam_score, sum(0), average; // Declare and initialize objects. int counter; // Prompt user for input. cout << "Enter the number of exam scores to be read "; 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; // Calculate average exam score. average = sum/counter; cout << counter << " students took the exam.\n"; cout << "The exam average is " << average << endl; // Exit program return 0; WHAT IS FINAL OUTPUT FOR 3 10 20 30?
Sentinel-Controlled Loops May be used for reading input data if a special data value exists that can be used to indicate the end of data.
SENTINEL CONTROL */ /* This programs finds the average of a set of exams */ #include<iostream> //Required for cin, cout using namespace std; int main() // Declare and initialize objects. double exam_score, sum(0), average; int count(0); // Prompt user for input. cout << "Enter exam scores separated by whitespace. "; // Input exam scores using end-of-data loop. cin >> exam_score; while(exam_score>=0) what value(s) terminates the loop? sum = sum + exam_score; ++count; cin >> exam_score; // Calculate average exam score. average = sum/count; cout << count << " students took the exam.\n"; cout << "The exam average is " << average << endl; // Exit program return 0;
End-of-data Controlled Loops Is the most flexible for reading input data. No prior knowledge of the number of data values is required. No sentinel value is required. We use a function called cin.eof() returns 0 when special input signally end of data. This eof = end of file used here (also used in files) is system defined. Key board entry for cin.eof()! Use different ctrl + some key? to indicate no more data will be entered Our system uses ctrl z anything else will send your output to computer heaven!
End of Data Loop /* Program chapter4_7 */ /* This programs finds the average of a set of exam scores. */ #include<iostream> //Required for cin, cout using namespace std; int main() // Declare and initialize objects. double exam_score, sum(0), average; int count(0); // Prompt user for input. cout << "Enter exam scores separated by the enter key. "; // Input exam scores using end-of-data loop. cin >> exam_score; while(!cin.eof()) note use of! sum = sum + exam_score; ++count; note use of count here. cin >> exam_score; // Calculate average exam score. average = sum/count; cout << count << " students took the exam.\n"; cout << "The exam average is " << average << endl; // Exit program return 0;
RUN NOW in class A VERSION OF THE LAST program online prog4_7 study the program before you run it! Add the following exam numbers for the average 56 76 78 What did you use to terminate the input? Run again and try something different to terminate? What is the average your program produces.
Problem Solving Applied: Weather Balloons Weather Balloons gather info on the atmosphere as the rise. Temperature and pressure. They are filled with helium and they rise to a Specific altitude where the upward buoyant force is balanced by gravity (equilibrium) but as the air temperature changes during the day and night the The balloon will expand and contract and rise higher and lower with air Temperature.. Thus the altitude of the balloon changes as the hours go by. alt(t)= -0.12t 4 +12t 3-380 t 2 +4100t +220 t in hours alt in meters The velocity of the balloon is max at the start and as it ascends it will stop at Its maximum height and then the velocity changes direction as it descends to a minimum and stop there before rising again, this pattern continues. v(t)= -0.48t 3 +36t 2-760t +4100 The graph below for 48 hrs shows this situation
Problem statements: Weather Balloons to construct a flow chart first. User enters the following 3 items Output expected
Problem Solving Applied: Weather Balloons: Checking our program! We want to produce this table and its maximum alt and time to be sure We coded our program properly before going on to more time data.
Weather Balloon Project: 1. construct the flow chart for this weather balloon project to hand in with the program. You may find the GPS flowchart useful 2. Write the code and produce the table to be sure your code is tested and attach to the code as usual. 3. Run the program for the 48 hours and attach output with the maxium alt found. 4. Answer this question does your data and conclusion in 3 match the curves of alt and v given in the power points and in the text
HW Exam practice pages 176-177 questions 1-16 to hand in.
-