Study recommendations for the Mid-erm Exam - Chapters 1-5 Review Chapters 1-5 in your textbook, the Example Pages, and in the Glossary on the website Standard problem solving steps used in program development (in order): ANALYSIS: LOGICAL DESK WORK 1. Define the ask or Objectives 2. Define the Output 3. Define the Input 4. Define the Algorithm 5. Check the Algorithm PROGRAMMING: PHYSICAL CODING 6. Code the Program in a high-level language such as C++ 7. Debug the Program he three types of errors common in programming are: 1. Logic errors: mistakes made in the design of an algorithm - minimized by doing desk checks. 2. Syntax errors: mistakes in use of the programming language when writing source code - detected by the compiler during each attempted compilation. 3. Run-time errors: mistakes occurring during an execution of a program, usually resulting from the entry of unexpected data or some hardware problem. he rules of syntax for defining valid identifiers in the C++ Language: Identifiers can contain only letters (either case), numerals, or the underscore character ( _ ), although identifiers starting with an underscore had special restrictions and an identifier consisting of only a lone underscore is forbidden. No blank spaces or special characters are allowed; nor should you use double underscores. Identifiers cannot start with a digit. A C++ reserved word cannot be used as an identifier. Identifiers are case sensitive. he maximum length of an identifiers depends on the compiler being used, but most allow at least 1024 characters (although such lengths would be extremely impractical). Quiz preparation exercise: Circle the labels that are NO valid variable names under the rules of syntax for C++. cout xyz2 int Sue's 4th abc$ my2nd Note that cout is a standard identifier in C++ but not a reserved word, like int. Rev. 2012-10-18 Page 1 of 13
Order of Precedence able (including arithmetic, relational and Boolean operators): () Highest / irst postfix ++ postfix -- ^! prefix ++ prefix -- unary + unary - unary & casts * / % + - < > <= >= ==!= && Lowest / Last Quiz preparation exercise: In each of the four separate expressions below, circle the operator of the arithmetic operation that will be performed first. X / Y / Z ( X * ( M - N ) ) / Y Quiz preparation exercise: X - Y * Z Z / ( X - Y ) Circle any (and all) SYNAX errors in the following C++ statements and describe them briefly on the line provided. Do NO mention logical errors. If a line is valid, answer "OK". Each line is a separate question, independent of the others. #include <iostream>; #define ACOR = 9 const int MAX ; float = AM; Compiler directives are not terminated by a semi-colon Assignment is not used with a symbolic constant Named constants must be initialized when defined Equal sign can be used only after an identifier to initialize X = X * 2; OK (this statement simply doubles X) cout << Hello; // Display Hello loat AM,PAY,AX=10.0; String constants should be enclosed in double quotes he keyword float is all lowercase / his is a comment / Comments must be inside /* and */ pairs or preceded by // NUM = 100 / ( AM + 5 ) cin << AM; // Read keyboard cout >> Hello; cout << precision(4) << 12345; he statement terminating semi-colon is missing cin should use the >> stream extraction operator he << (stream insertion) operator belongs with the cout object he precision manipulator is named setprecision Rev. 2012-10-18 Page 2 of 13
cout << left(2) << 12.345; C = static-cast<float>(a) / B; cout << "Hello"\n; he left manipulator uses no arguments he keyword static_cast contains an underscore rather than a hyphen he \n escape sequence should be inside the quotes Quiz preparation exercise: or each of the following logical statements, write one C++ statement to perform the specified task. Assume that these tasks are all a part of a restaurant-bill-calculating program using identifiers as shown below: LABEL DESCRIPION SOURCE USAGE DESINAION PUR Amount of the purchase Assigned for AX & PAY --- AX Calculated sales tax Calculation for PAY --- PAY otal amount to pay after tax Calculation - Displayed 1. Allocate (set aside) storage for the three variables that may have decimal points. double PUR,AX,PAY; // Note: the float data type would also be OK for small values 2. Display the program title "AX PROGRAM" on a line of its own. cout << " AX PROGRAM\n "; // or cout << " AX PROGRAM" << endl; 3. Assign the value 123.45 into the variable that holds the purchase. PUR = 123.45; 4. Calculate and store the tax as 6% of the purchase amount. AX = 0.06 * PUR; 5. Display the string "Please pay $" followed by the total amount to pay rounded to cents, followed by a carriage return. cout << "Please pay $" << setprecision(2) << fixed << PAY << endl; Rev. 2012-10-18 Page 3 of 13
Output ormatting Examples Review the following examples of formatted output statements paying close attention to the format of the resulting output beside them. Each box indicates one character position on the screen. All output starts in the leftmost box, although some output might be "padded" with blank spaces to align it to the right edge of the field. "X"'s indicated unused positions. C++ command using cout with various stream manipulators (assuming default values for any missing manipulators) cout << setw(3) << 'A'; Output Produced on Screen Position: 1 1 1 1 1 1 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 A X X X X X X X X X X X X cout << setw(3) << left << 'A'; A X X X X X X X X X X X X cout << setw(8) << "ABCD"; cout << 52; cout << setw(8) << 52; A B C D X X X X X X X 5 2 X X X X X X X X X X X X X 5 2 X X X X X X X cout << setw(8) << left << 52; 5 2 X X X X X X X cout << 123.456; cout << setw(10) << setprecision(2) << fixed << 123.456; cout << setw(10) << setprecision(6) << fixed << showpoint << 123.456; cout << setw(10) << setprecision(2) << fixed << left << 123.456; cout << setprecision(2) << fixed << 123.456; cout << setw(10) << setprecision(3) << fixed << -45.8; cout << setw(10) << 0.00085; 1 2 3. 4 5 6 X X X X X X X X 1 2 3. 4 6 X X X X X 1 2 3. 4 5 6 0 0 0 X X X X X 1 2 3. 4 6 X X X X X 1 2 3. 4 6 X X X X X X X X X - 4 5. 8 0 0 X X X X X 0. 0 0 0 8 5 0 X X X X X Rev. 2012-10-18 Page 4 of 13
SELECION SRUCURES: Structures such as the one on the left are coded in C++ using the reserved word if. Set X to 1 Set A to 0 A > 0 and A < 9 Replace X with triple its original value. he diamond shape encloses the condition that is being tested (in this example, a Boolean expression). Remember that the C++ if statement can only execute one statement on each leg ( or ), so the pair of steps on the alse leg must be coded inside of a and pair to make them a single compound statement. hus the C++ code would be: if (A>0 && A<9) X=X*3; else X=1; A=0; Note the use of the parentheses around the condition in the code above. Additional parentheses are often necessary because of the order of precedence of operators in C++ (see the table on the previous page). Remember also that the alse leg may be empty, but not the rue leg. If your flowchart shows the opposite, then reverse the labeling of the rue and alse legs and reverse the logic of the condition inside the diamond. If you can't determine what the logical opposite of the condition would be, simply use the NO operator like this:! ( A>0 && A<9 ) ruth ables for Boolean Operators: (Op = Operand, a relational expression or Boolean value) Op.A Op.B Op.A && Op.B Op.A Op.B Op.A Op.B Op.A! ( Op.A ) Rev. 2012-10-18 Page 5 of 13
CASE Selection C++'s switch statement can be used in the special situation that you are testing for many possible values in a single ordinal storage location. In the example below, five possible paths might be followed depending on the value stored in the character storage location X. Each path (leg) is selected based on the individual value(s) that might be stored in X. he C++ code would be: A 1 X "A" "B" "C" "D","E" else A 2 Y 1 A 3 A 4 A 0 switch (X) case 'A': A=1; break; case 'B': A=2; Y=1; break; case 'C': A=3; break; case 'D': case 'E': A=4; break; default: A=0; break; Notice: (1) the parentheses around the character expression (X) (2) the inclusion of "break;" after each option serving to brace any multiple statements on each leg (3) the braces used to enclose the full list of options. he use of indentation and the positions of the carriage returns in the code are irrelevant. ( Continued on next page ) Rev. 2012-10-18 Page 6 of 13
SAMPLE QUESIONS: (AND ANSWERS) Draw a flowchart that matches the following code. Answer: Start X N = 30 if (N == 0); cout << "Yes"; End Yes Notice that the semicolon which follows the condition N==0 terminates the if statement, making it pointless. he cout statement will be executed regardless of the condition's value. Draw a flowchart that matches the following code. if (X == 3) Y = 4; Z = 5; Answer: Start End X = 3 Z 5 Y 4 Notice that the Z = 5 step follows the selection. It is not part of the true leg because it was not included inside of a pair of braces. he semicolon following the Y = 4 statement terminated the if statement. Circle any SYNAX (not run-time) ERRORS (there may be more than one) in each of the following C++ code segments. If a segment is valid answer "OK". Assume all variables already have been correctly declared. cin >> A; if ( A<10 && >20 ) cout << "ok"; >20 is not a complete relational expression X=1; cin >> Y; if X > Y cout << "OK" else cout << "NO"; missing parentheses around condition and missing semi-colon after if statement Rev. 2012-10-18 Page 7 of 13
Indicate the Boolean results (RUE or ALSE) for each of the following expressions, given: #define S "123" /* a string of numerals */ int A=0, B=2, C=-3; A==0 B<2 && C<0!(A>C) && A<C A!=0 B<2 S>"8" rue alse alse alse S>100 Logically invalid (data type mismatch) Given the following declarations for employee data within a program: int A; /* Age */ char D; /* Highest Degree Earned (only possible values are uppercase: 'N' = None, 'B' = Bachelor's, 'M' = Master's, or 'D' = Ph.D.) */ char G; /* Gender (only uppercase 'M' or '' are possible) */ Write a compound If statement in C++ that will display the message "OK" only when the employee is a female, between the ages of 20 and 30 (inclusive) and holds a college degree (Bachelor's, Master's or Ph.D.). Do NO check for case. Assume that previous statements have guaranteed uppercase values only, so that you need only check for uppercase values. Answer: if ( G== && A>=20 && A<=30 && ( D== B D== M D== D ) ) cout << "OK"; REPEIION SRUCURES: Structure: We studied two repetition structures (loops); one known as leading decision (a.k.a. pretest) and another known as trailing decision (a.k.a. posttest). he primary difference between them is in where the test that controls the loop is performed. Leading decision loops test before each pass and are coded in C++ using while (condition) body_statements; railing decision loops test after each pass and are coded in C++ using do body_statements; while (condition); We can design a loop that test somewhere in the middle, but that is consider very poor programming practice. Control: We studied two methods of controlling loop passage and exit. Counting control is based on the testing of values that have been set and altered by the programmer. Programmers know in advance how many times any counting loop will pass (execute its body) because all values of its control variable are predictable. Sentinel Rev. 2012-10-18 Page 8 of 13
control is based on the testing of external values that have been read into the program. Programmers do not know in advance how many times a sentinel loop will pass (execute its body) because the values of its control variable are unpredictable. Boundary Values: he values of variables just prior to the entry into a loop and just after the exit from a loop are called boundary values. Steps inside a loop can be organized so that the value of a variable is changed after it is displayed, so don't expect that variables will always contain the last value that you saw displayed. Counting Loops: All counting loops have at least four parts: initialization - prior to the loop entry, a first value of the control variable is set body - where the step(s) to be repeated belong increment (or decrement) - where the control variable is increased (or decreased) test - where the control variable is tested to determine whether the loop should pass or exit. he bottom three steps are not always in the order listed above. he order of the steps will affect the boundary values of the control variable. he two examples below show loops that will count from 1 to 9 and display the value of the control variable (also called a counter in a counting loop). Notice the exit value on N will be 10. N 1 N=1; N 1 N=1; while (N<=9) do N<=9 N cout <<N<<endl; N cout <<N<<endl; N = N+1; N N+1 N = N+1; N N+1 N <= 9 while (N<=9); If a loop: (1) uses the Leading Decision structure, (2) uses counting control, and (3) increments as the last step of its pass, C++ offers a special "automatic loop" statement combining the statements above (on the left) into the single statement: for (N=1; N<=9; N=N+1) cout << N << endl; Note: if the body of the loop has more than one statement to repeat, block it inside of braces. Most common coding errors when writing source code for loops: Closing the loop statement too soon with a misplaced semicolon ailing to block a body with multiple statements inside of braces orgetting the difference between the operators = (assignment) and == (equality) Rev. 2012-10-18 Page 9 of 13
SAMPLE QUESIONS: (AND ANSWERS) Circle any SYNAX (not run-time) ERRORS (there may be more than one) in each of the following C++ code segments. If a segment is valid answer "OK". Assume all variables have been correctly declared. for (I=1, I<=79, I++) cout << "-"; the commas (,) should be semi-colons (;) X=1; while X < 5 cout << X++; missing parentheses around condition Use the following for Statement to answer the next 3 questions (A-C). for (Count=Start; Count<=inish; Count++) cout << Count; (A) Which variable is the "control variable"? Count (B) What does Count++ mean? _Increment Count by 1 after a pass is complete (C) If Start contains a value of -4 and inish contains the value 0, how many times will the loop execute? Answer: 5 lowchart a program with a loop that accumulates whole numbers entered by the user until a -1 is entered and then identifies and displays the sum. hen write the C++ code to the right of it. Start ot 0 N is not -1 Sum is: ot Number (-1 to stop)? N N is not -1 ot ot + N End /* accumulate.cpp */ #include <iostream> using namespace std; int main () int N, ot=0; do cout << "Number (-1 to stop)? "); cin >> N; if (N!= -1) ot = ot + N; while (N!= -1); cout << "Sum is: " << ot << endl; return 0; Rev. 2012-10-18 Page 10 of 13
or each question below, circle any and all loop control methods for which the claims are true: (A) his control method is based on values assigned by the programmer, not given by the user. counting sentinel (B) his control method is based on values entered by the user. counting sentinel (C) he number of passes that the loop will perform can always be predetermined when the loop starts. counting sentinel or each question below, circle any and all loop structures for which the claims are true: (A) he test for each repetition is performed after the pass through the loop body. leading decision trailing decision (B) he body will always be executed at least once. leading decision trailing decision (C) his structure is appropriate for sentinel controlled loops that use a "prime read". leading decision trailing decision (D) Sentinel controlled loops using this structure need an extra test to guard the body from the sentinel value. leading decision trailing decision DISK ILE INPU AND OUPU: Review the last part of Chapter 5 in your textbook that discuss reading and writing of sequential text files on disks. hen study the practice exercise on the following page. It involves a file with a simple name that is located in the same folder as the program. Be aware that special consideration must be given when providing filenames or paths that contain whitespaces or characters that C++ interprets as having special meaning, such as backwards slashes. or example, to open a file named "My ile.txt" entered at the keyboard, you would need to input the string using the getline() function to prevent the whitespace from truncating the portion of the filename starting at the whitespace before assigning it to a string variable, as in: getline (cin, StringVar); // read a string containing whitespaces Rev. 2012-10-18 Page 11 of 13
o associate a file accessible from the disk location "C:\User\JStudent\Data.txt" with a file input stream object named "inile", you would have to escape the backwards slashes (\) as follows: inile.open("c:\\user\\jstudent\\data.txt "); Examine the following C++ source code: /************************************************************ * Program: diskio.cpp - Practice Exercise * * Opens a file in the same folder as the program based on a * * user supplied name (without whitespaces). hen writes ten * * lines of text, closes the file, then reopens the file and * * reads and displays each of the ten lines from the file. * ************************************************************/ #include <iostream> #include <fstream> using namespace std; int main () string ILENAME; // String object to hold a filename system ("cls"); /* Clear the Screen */ cout << "Disk I/O Program\n\n"; cout << "What is the filename (w/o path)? "; cin >> ILENAME; ofstream fileout; fileout.open(ilename.c_str()); // open requires a C-String if (fileout) // Verify successful open cout << ILENAME << " opened successfully for writing.\n\n"; for (int C=1; C<=10; C++) fileout << "Line " << C << endl; fileout.close(); else cout << ILENAME << "\a failed to open.\n"; string OSR; ifstream filein; filein.open(ilename.c_str()); if (filein) cout << ILENAME << " opened successfully for reading.\ncontents:\n"; for (int C=1; C<=10; C++) getline(filein,osr); // read a line of text with whitespaces cout << OSR << endl; Rev. 2012-10-18 Page 12 of 13
filein.close(); else cout << ILENAME << "\a failed to open.\n"; system ("pause"); return 0; Rev. 2012-10-18 Page 13 of 13