13
COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide Rev. 2012-10-18 Page 1 of 13 Study recommendations for the Mid-Term 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 Task 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 The 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. The 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. The 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 NOT 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.

Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

  • Upload
    vudung

  • View
    218

  • Download
    4

Embed Size (px)

Citation preview

Page 1: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 1 of 13

Study recommendations for the Mid-Term 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 Task 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

The 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. The 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. The 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 NOT 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.

Page 2: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 2 of 13

Order of Precedence Table (including arithmetic, relational and Boolean operators):

() Highest / First

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 X - Y * Z Z / ( X - Y )

Quiz preparation exercise: Circle any (and all) SYNTAX errors in the following C++ statements and describe them briefly on the line provided. Do NOT mention logical errors. If a line is valid, answer "OK". Each line is a separate question, independent of the others. #include <iostream>; Compiler directives are not terminated by a semi-colon

#define FACTOR = 9 Assignment is not used with a symbolic constant

const int MAX ; Named constants must be initialized when defined float = AMT; Equal sign can be used only after an identifier to initialize

X = X * 2; OK (this statement simply doubles X)

cout << Hello; // Display Hello String constants should be enclosed in double quotes

Float AMT,PAY,TAX=10.0; The keyword float is all lowercase

/ This is a comment / Comments must be inside /* and */ pairs or preceded by //

NUM = 100 / ( AMT + 5 ) The statement terminating semi-colon is missing

cin << AMT; // Read keyboard cin should use the >> stream extraction operator cout >> Hello; The << (stream insertion) operator belongs with the cout object

cout << precision(4) << 12345; The precision manipulator is named setprecision

Page 3: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 3 of 13

cout << left(2) << 12.345; The left manipulator uses no arguments

C = static-cast<float>(A) / B; The keyword static_cast contains an underscore rather than a hyphen

cout << "Hello"\n; The \n escape sequence should be inside the quotes Quiz preparation exercise: For 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 DESCRIPTION SOURCE USAGE DESTINATION PUR Amount of the purchase Assigned for TAX & PAY --- TAX Calculated sales tax Calculation for PAY --- PAY Total amount to pay after tax Calculation - Displayed 1. Allocate (set aside) storage for the three variables that may have decimal points.

double PUR,TAX,PAY; // Note: the float data type would also be OK for small values

2. Display the program title "TAX PROGRAM" on a line of its own.

cout << " TAX PROGRAM\n "; // or cout << " TAX 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.

TAX = 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;

Page 4: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 4 of 13

Output Formatting 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)

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

cout << setw(3) << 'A'; 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"; A B C D X X X X X X X

cout << 52; 5 2 X X X X X X X X X X X X X

cout << setw(8) << 52; 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; 1 2 3 . 4 5 6 X X X X X X X X

cout << setw(10) << setprecision(2)

<< fixed << 123.456; 1 2 3 . 4 6 X X X X X

cout << setw(10) << setprecision(6)

<< fixed << showpoint << 123.456; 1 2 3 . 4 5 6 0 0 0 X X X X X

cout << setw(10) << setprecision(2)

<< fixed << left << 123.456; 1 2 3 . 4 6 X X X X X

cout << setprecision(2) << fixed <<

123.456; 1 2 3 . 4 6 X X X X X X X X X

cout << setw(10) << setprecision(3)

<< fixed << -45.8; - 4 5 . 8 0 0 X X X X X

cout << setw(10) << 0.00085; 0 . 0 0 0 8 5 0 X X X X X

Page 5: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 5 of 13

SELECTION STRUCTURES: Structures such as the one on the left are coded in C++ using the reserved word if. The 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 (T or F), so the pair of steps on the False leg must be coded inside of a { and } pair to make them a single compound statement. Thus 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 False leg may be empty, but not the True leg. If your flowchart shows the opposite, then reverse the labeling of the True and False 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 NOT operator like this: ! ( A>0 && A<9 )

Truth Tables 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 ) F F F F F F F T F T F F T T T F T F F T F T T T T T T T

Replace X with triple its original value.

Set X to 1

Set A to 0

A > 0

and

A < 9

T F

Page 6: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 6 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. The C++ code would be:

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. The use of indentation and the positions of the carriage returns in the code are irrelevant.

( Continued on next page )

X

A2

Y1

A3 A4 A1 A0

"A" "B" "C" "D","E" else

Page 7: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 7 of 13

SAMPLE QUESTIONS: (AND ANSWERS)

Draw a flowchart that matches the following code. Answer:

if (N == 0); cout << "Yes";

Notice that the semicolon which follows the condition N==0 terminates the if statement, making

it pointless. The cout statement will be executed regardless of the condition's value.

Draw a flowchart that matches the following code. Answer:

{

if (X == 3) Y = 4;

Z = 5;

}

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. The semicolon following the Y = 4 statement terminated the if statement. Circle any SYNTAX (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" missing parentheses around condition and

else cout << "NO"; missing semi-colon after if statement

X = 3

T

F

Start

End

Start N = 0

T

F

Start Start

Y4

Z5

X = 3

T

F

Start

End

Start

Yes

Page 8: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 8 of 13

Indicate the Boolean results (TRUE or FALSE) 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 True

!(A>C) && A<C False

A!=0 || B<2 False

S>"8" False

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 'F' 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 NOT check for case. Assume that previous statements have guaranteed uppercase values only, so that you need only check for uppercase values.

Answer:

if ( G==’F’ && A>=20 && A<=30 && ( D==’B’ || D==’M’ || D==’D’ ) )

cout << "OK";

REPETITION STRUCTURES:

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). The 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; }

Trailing 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

Page 9: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 9 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:

The 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.

The bottom three steps are not always in the order listed above. The order of the steps will affect the

boundary values of the control variable.

The 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;

while (N<=9) do

{ {

cout <<N<<endl; cout <<N<<endl;

N = N+1; N = N+1;

} }

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

Failing to block a body with multiple statements inside of braces

Forgetting the difference between the operators = (assignment) and == (equality)

N1

NN+1

F

T

N<=9

N

N1

NN+1

N

F T N <= 9

Page 10: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 10 of 13

SAMPLE QUESTIONS: (AND ANSWERS)

Circle any SYNTAX (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 missing parentheses around condition cout << X++;

Use the following for Statement to answer the next 3 questions (A-C).

for (Count=Start; Count<=Finish; 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 Finish contains the value 0, how many times will

the loop execute? Answer: 5

Flowchart 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. Then write the C++ code to the right of it.

/* accumulate.cpp */

#include <iostream>

using namespace std;

int main ()

{

int N, Tot=0;

do

{

cout << "Number (-1 to stop)? ");

cin >> N;

if (N != -1) Tot = Tot + N;

}

while (N != -1);

cout << "Sum is: " << Tot << endl;

return 0;

}

N is not -1

Tot Tot + N

Number (-1 to stop)?

F

F

Start

Tot 0

N

N is not -1

T

T

End Sum is: Tot

Page 11: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 11 of 13

For each question below, circle any and all loop control methods for which the claims are true:

(A) This control method is based on values assigned by the programmer, not given by the user.

counting sentinel

(B) This control method is based on values entered by the user.

counting sentinel

(C) The number of passes that the loop will perform can always be predetermined when the loop starts.

counting sentinel For each question below, circle any and all loop structures for which the claims are true:

(A) The test for each repetition is performed after the pass through the loop body.

leading decision trailing decision

(B) The body will always be executed at least once.

leading decision trailing decision

(C) This 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 FILE INPUT AND OUTPUT: Review the last part of Chapter 5 in your textbook that discuss reading and writing of sequential text files on disks. Then 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. For example, to open a file named "My File.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

Page 12: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 12 of 13

To associate a file accessible from the disk location "C:\User\JStudent\Data.txt" with a file input stream object named "inFile", you would have to escape the backwards slashes (\) as follows: inFile.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). Then 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 FILENAME; // 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 >> FILENAME;

ofstream fileOut;

fileOut.open(FILENAME.c_str()); // open requires a C-String

if (fileOut) // Verify successful open

{

cout << FILENAME << " opened successfully for writing.\n\n";

for (int C=1; C<=10; C++) fileOut << "Line " << C << endl;

fileOut.close();

}

else cout << FILENAME << "\a failed to open.\n";

string OSTR;

ifstream fileIn;

fileIn.open(FILENAME.c_str());

if (fileIn)

{

cout << FILENAME << " opened successfully for reading.\nContents:\n";

for (int C=1; C<=10; C++)

{

getline(fileIn,OSTR); // read a line of text with whitespaces

cout << OSTR << endl;

Page 13: Study recommendations for the Mid-Term Exam - · PDF fileStudy recommendations for the Mid-Term Exam ... circle the operator of the arithmetic operation that will be ... write one

COP 2000 - Introduction to Computer Programming I Mid-term Exam Study Guide

Rev. 2012-10-18 Page 13 of 13

}

fileIn.close();

}

else

cout << FILENAME << "\a failed to open.\n";

system ("pause");

return 0;

}