PIC 10A sec. 3


Instructor: Ivo Dinov, Asst.Prof.

Mathematics, Neurology, Statistics


Midterm Study Guide


Exam: Fri., May 04, 2001, 12:00-12:50 PM, UCLA LS 2147



I. Part One:


1 Answer the following questions:

a)How many bits are in 1 byte? .

b)How many bytes are in 1MB?

c)Computers process data under the control of sets of instructions called computer ………….?

d)What are the  logical units of the computer?

f)What are the programs that translate high-level language programs into machine language called?


2 Fill in the blanks in each of the following sentences about the C++ environment.

a)C++ programs are normally typed into a computer using an ……….program.

b)In a C++ system, a program executes before the compiler’s translation phase begins………….

c)The program ………….combines the output of the compiler with various library functions to produce an executable image.

d)The program …………..transfers the executable image of a C++ program from disk to memory.


3 Fill in the blanks in each of the following.

a)Every C++ program begins execution at the function ……… .

b) ……..  begins the body of every function and ………… ends the body of every function.

c)Every statement ends with a …...

d)The escape sequence \n represents the character which causes the cursor to

position to the beginning of the next line on the screen.

e)The statement ……..is used to make decisions.


4 State whether each of the following is true or false .

   If false, explain why. Assume the statement using std::cout; is used.

a)Comments cause the computer to print the text after the //on the screen when the program is executed.

b)The escape sequence \n when output with cout causes the cursor to position to the beginning of the next line on the screen.

c)All variables must be declared before they are used.

d)All variables must be given a type when they are declared.

e)C++ considers the variables number and NuMbEr to be identical.

f)Declarations can appear almost anywhere in the body of a C++ function.

g)The modulus operator (%) can be used only with integer operands.

h)The arithmetic operators *,/,%,+and -all have the same level of precedence.

i)A C++ program that prints three lines of output must contain three output statements using cout .


5 Write a single C++ statement to accomplish each of the following

a)Declare the variables c ,thisIsAVariable ,q76354 and number to be of type int .

b)Prompt the user to enter an integer. End your prompting message with a colon (:)followed by a space and leave the cursor positioned after the space.

c)Read an integer from the user at the keyboard and store the value entered in integer variable age .

d)If the variable number is not equal to 7 ,print "The variable number is not equal to 7".

e)Print the message "This is a C++ program" on one line.

f)Print the message "This is a C++ program" on two lines where the first line ends

with C++.

g)Print the message "This is a C++ program" with each word of the message on a separate line.

h)Print the message "This is a C++ program"with each word separated from the next by a tab.


6 Write a statement (or comment) to accomplish each of the following

a)State that a program will calculate the product of three integers.

b)Declare the variables x ,y ,z and result to be of type int .

c)Prompt the user to enter three integers.

d)Read three integers from the keyboard and store them in the variables x ,y and z .

e)Compute the product of the three integers contained in variables x ,y and z ,and assign the result to the variable result .

f)Print "The product is "followed by the value of the variable result .

g)Return a value from main indicating that the program terminated successfully.


7 Using the statements you wrote in Exercise 6,write a complete program that calculates and displays the product of three integers. Note: you will need to write the necessary using statements.


8 Identify and correct the errors in each of the following statements , if there are any:

a)if (c <7 );

cout <<"c is less than 7 \n";

b)if (c =>7 )

cout <<"c is equal to or greater than 7 \n";



II. Part Two:


Multiple choice questions may have more than one correct answer. The student is to give all correct answers to multiple choice questions. True-false questions require explanation. Other questions may require an explanation.


1. Describe top down design. Give some of the advantages of top down design.


2. Which of the following are true, which are false? Why?


Top down design provides the following advantages and/or disadvantages:

   a) makes a program easier to understand

   b) makes a program harder to change

   c) makes a program easier to test and debug

   d) makes a program easier to maintain

   e) makes team programming easier


3. On every system there is a file you must include to use the math library. Show how to do this, and explain what is in this file.


4. Mark the following True or False, and explain.


   a) The header files, such as math.h, contain the libraries.

   b) The header files, such as math.h, contain declarations of the

       functions in the associated library, such as the math library.

   c) The functions in the math library are attached to your program

       by the compiler during the linking phase of compilation.

   d) On the system I use to do my homework, I have to tell the compiler

     to connect the library functions to my program.



5. Here is a complete function that purports to return one of the roots of a quadratic given the coefficients of the square, a, linear, b, and constant, c, terms. It fails to compile. Why?


   //returns one of the roots of the quadratic equation

   //a*x*x + b*x + c = 0

   double root1 (double a, double b, double c)


       return (-b + sqrt(b*b - 4 * a * c))/(2*a);



6. What if anything is wrong with the following #include <...> directives?

   a) #include < iostream.h>

   b) #include <Iostream.h>

   c) #include <iostream.h>

   d) #include <iostream>

   e) #include iostream.h


7. Matching: Which of the header files listed first below contain declarations of the function on the second list?


   A. iostream.h

   B. stdlib.h

   C. math.h


   a) ____ int abs(int);

   b) ____ double sqrt(double);

   c) ____ cout << a_double;

   d) ____ double fabs(double);

   e) ____ double pow (double base, double exponent);

   f) ____ long labs(long);

   g) ____ cout.setf(/* formatting constant(s) */);


8. Given the following include directive (to get the declaration for the pow function from the math library):


      #include <math.h>


Now make these declarations:


      double base = 2, exponent = 3, power = 4;


Which of the following are correct invocations for the pow function? If any of the following is correct, give the value assigned, and if

apparently incorrect, explain.


   a) power = pow(base, exponent);

   b) pow(power, base, exponent);

   c) pow(base, exponent) = power;

   d) base = pow(exponent, power);


9. Convert the following mathematics expressions to C++ expressions. Use the declarations provided. Use library functions only where you cannot do without. Include the appropriate header file for any library function used. Be sure you initialize any variables whose values you are using to reasonable values for the library functions you are using.


      int x, y; //declaration for a) and b)

      a) y = x3

      b) y <= |x|


      double x, y, z, area; //declaration for c) through e).

   c) z = x1.6

   d) z = area

   e) p =


10. None of the following assignments do what the programmer expects. Give, or describe the actual effect or result, and correct the code to get a result that may be reasonably expected. (You may add casts, changing double to int or int to double, etc.)


   a) double z = 9/4;

   b) int PI = 3.1415926;

   c) double C, F;

      F = (9/5) * C + 32.0;

   d) double C, F;

      F = double(9/5) * C + 32.0;


11. Write code that declares x, y, and z as double variables. Then write code that causes z to be assigned the result of x divided by

y, rounded as indicated below. Be sure to #include the header file that declares the library functions you use.


   a) round up

   b) round down

   c) round to the nearest integer. Does your code round an exact half up or down? say 2.5?


12. Each of the following lines of code purport to round the results of the division of doubles to the nearest integer value (but still of

type double). All are correct C++ code but some do not round correctly. Tell which rounds down, up, or to the nearest integer

value, or is not reasonable

Assume that math.h has been included, and that all variables have appropriate values.


   double x, y, z;

   a) z = ceil(x/y);

   b) z = ceil(x/y - 0.5);

   c) z = floor(x/y - 0.5);

   d) z = floor(x/y + 0.5);

   e) z = floor(x/y);


13. Declare (give a prototype for) a function named average_grade. This function returns  a double and has four double

arguments, test1, test2, test3, test4. Be sure to include a "prototype comment" that tells briefly what the function does.


14. Define a function named average_grade. This function returns a double and has four double arguments, test1, test2, test3,

test4. The return value should be the average, or arithmetic mean of the four arguments. Be sure to include a comment that tells

briefly what the function does.


15. Give an outline for the general form of a programmer defined function.


16. Given the function,


   // returns the sum of the arguments.

   double Sum (double a, double b)


       return a + b;



Write statement that calls to this function. The call should pass the values of doubles x and y, and assign the returned value to a

double, z.


17. In your own words discuss similarities and differences between a function and a small program.


18. What output is produced by the following program? Explain briefly.


   // file Test.cc

   #include <iostream>

   using namespace std;


   char mystery(int first_par, int second_par);

   int main()


       cout << mystery(10, 9) << "ow" << endl;

       return 0;


   // what this does is the test question is all about!

   char mystery(int first_par, int second_par)


       if (second_par >= first_par)

           return 'W';


           return 'H';



19. When you call a function there must be a match between the ________ and _________ of  arguments and parameters


20. Given the function declaration (prototype), does the compiler complain or compile if you call this using the following line? If the

compiler complains, what is the complaint?


   //if score >= min_to_pass, returns 'P' for passing,

   //else returns 'F' for failing.

   char grade (int score, int min_to_pass);

   double fscore;

   char fgrade;

   int need_to_pass;

   int main()


       //omitted code to get values for variables

       //fscore and need

       fgrade = grade(fscore, need);

       return 0;



21. What should the contents of the 'prototype comment' be? The prototype comment is the comment that the text suggests

strongly should accompany a function declaration (prototype).


22. The text compares function usage to the idea of black box. Describe in your words what a black box is.


23. In your own words, discuss procedural abstraction.


24. True or False: Every programmer must know all the details of what that programmer's team mates are doing in their projects to

do the work assigned. Why?


25. True or False: Procedural abstraction involves information hiding in that only the 'contract' between the programmer using the

function (the client) and author of a function is known to either.


26. Procedural abstraction requires the author of a function and the client (user) of that function to know and not to know certain

things. Remark on who needs to and who should not know each of the following items


   a) the requirements on the parameter values,

   b) exactly what the return value is to be,

   c) the implementation details, and

   d) the details of how the function is used by the client.


27. Which of the following variable names will likely contribute to clearly readable code. Why or why not?


   a) x

   b) xy

   c) xylene_volume

   d) length

   e) jamesage

   f) velocity

   g) acceleration

   h) u

   i) position

   j) cost_of_pizza


28. Given the declarations,


double radius, diameter;


which pairs of the following are the following produce equivalent results? Why? (The why is as important as the equivalence of the



   a) radius = diameter/2.0;

   b) radius = diameter/2;

   c) radius = diameter/double(2);

   d) All of the above produce the same results.


29. In testing code having an if or an if-else clause, describe how to construct test data. Give an example based on:


   if (x > y)



       if (u > v)





30. Answer the question at the end of this code.


   const int x = 1.23456789;

   int f(int y)


       int z;

       //body of function: int f(int)


   const int w = 9.987654321;

   int g(double u)


       int v;

       // body of function: int g(double)


   int main ()


       int m;

       double nn;

       // body of function main()

       m = g(nn);

       // ...

       m = f(x);

       return 0;



In which functions can each variable be accessed?


   a)x           e) w

   b)f           f) g

   c)y           h) v

   d)z           i) m



31. Why not make all variables non constant global variables, and avoid the bother of parameters for functions?


32. Describe the similarity and difference between a function's parameters and function's local variables.


III. Part Three:


             True-False and short answer questions require explanation.


1. Define stream, and give some examples.


2. Define object, and give some examples.


3. What are the characteristics that files have that ordinary program variables share? What are characteristics of files that are different from ordinary variables in a program?


4. True or False: The following are characteristics that a file and an int variable have in common.

 a) information can be retrieved from both

 b) both are known out side the program

 c) information can be stored in both

 d) can exist before, after, as well as during the program execution

 e) large quantities of information can be stored in either

 f) neither is known before or after a program executes, is known only during execution.


5. To use a file there are several steps that must be carried out. Give them, together with an example fetching information into a program variable. You select the types.


6. What is wrong with the following program:

            #include <fstream>

     using namespace std;


     int main()


         ifstream in_stream;

         in_stream.open(mydata );

         // other statements

         return 0;



7. What is wrong with the following program:

   #include <fstream>

   using namespace std;


   int main()


     ifstream in_stream;

     char myfile[21];

     cout << "Enter a file name to be processed: " << endl;

     cin >> myfile


     // other statements

     return 0;



8. True or False: A file in use in a program may be referred to by either the external file name or the program variable that is connected to the file in the open statement.


9. True or False: A file when ready for use in a program has two names. If true, what are they? If false, explain.


10. A programmer has read half of the lines in a file. What must the programmer do to the file to enable reading the first line a second time?


11. Name at least three member functions associated with an iostream object, and give examples of usage of each.


12. With streams, the operators << and >> have a convenient rule to tell which goes with cin and which goes with cout. State such a rule.


13. Define class, and give some examples of classes. Where are your example classes declared (what header file) and where are they defined?


14. Give the syntax for calling a member function,


where this function is a member of object Calling_Object.


15. Give code to open a file named infile.dat for reading, where the stream variable is in_stream. Show how to determine whether it is safe to proceed with read operations.  You are to terminate the program if it isn't safe to read. Be sure to include necessary #include files.


16. You have been writing a file whose external name is outfile.dat, with stream variable out_stream. You reach a point where you no longer need to send output to the file outfile.dat. How do you close these files?


17. You have been writing a file whose external name is outfile.dat, with stream variable out_stream. You reach a point where you no longer need to send output to the file outfile.dat. What are some reasons why you may need to close these files?


18. Here is a code segment that copies three integers from infile.dat to outfile.dat. What changes are necessary to make the output go to the screen? (The input is still to come from infile.dat.)

   // Problem for test. copies three int numbers between files.

   #include <fstream>

   using namespace std;


   int main()


     ifstream in_stream;

     ofstream out_stream;



     int first, second, third;

     instream >> first >> second >> third;

     out_stream << "The sum of the first 3" << endl

                << "number in infile.dat is " << endl

                << (first + second + third) << endl;



     return 0;



19. Give the include directive you need for each of the following functions. There are both library functions and member function of classes here.

There are two answers to at least one of these.

  a) exit

  b) close

  c) abs

  d) isupper

  e) sqrt

  f) fabs

  g) setf

  h) pow

  i) open


20. Declare a string variable, file_name capable of holding a 15 character file name.


21. Given the following string variable declaration and input statement.

  #include <iostream>

  using namespace std;


  char name[21];

  cout >> name;

Suppose this code segment is embedded in a correct program. What is the longest name that can be entered into the string variable name?


22. In formatting output, the following constants are used with the ios member function setf. What effect does each have?

  a) ios::fixed

  b) ios::scientific

  c) ios::showpoint

  d) ios::showpos

  e) ios::right

  f) ios::left


23. What output will be produced when the following code is executed? (Assume these lines are embedded in complete, correct programs, with

proper #include directives.)

   cout << "*";


   cout << 123

        << "*" << 123 << "*" << endl;

   cout << setw(5) << 123 << "*" << 123 << "*" << endl;


24. What output is produced by the following code, assuming these lines of code are embedded in a correct program?

   cout << "*" << setw(5) << 123;


   cout << "*" << setw(5) << 123;


   cout << "*" << setw(5) << 123 << "*" << endl;


25. What output is produced by the following code, assuming these lines of code are embedded in a correct program?

   cout << "*" << setw(5) << 123 << "*"

        << 123 << "*" << endl;


   cout << "*" << setw(5) << 123 << "*"

        << 123 << "*" << endl;



   cout << "*" << setw(5) << 123 << "*"

        << setw(5) << 123 << "*" << endl;


26. What output is sent to the file out.dat by the following code, assuming these lines of code are embedded in a correct program?

   ofstream fout;


   fout << "*" << setw(5) << 123 << "*"

        << 123 << "*" << endl;


   fout << "*" << setw(5) << 123 << "*"

        << 123 << "*" << endl;



   fout << "*" << setw(5) << 123 << "*"

        << setw(5) << 123 << "*" << endl;


27. What happens to output when data is sent to the output stream width that is wider than that set with the setw(int) manipulator, or equivalently, with cout.width(int)?


28. What is sent to screen when the following is executed, assuming that these lines of code are embedded in a correct, complete program? Explain

this behavior.

   cout << "*" << setw(3) << 123456 << "*" << endl;


29. You have to #include <iostream> and #include <iomanip> when you use a line of code such as

   cout << setw(8) << 123456 << endl;

but not when you do the exact equivalent thing, as in


   cout << 123456 << endl;

Why is this?


30. Write a function that will copy the contents of file in.dat to the file out.dat. Check for successful file opening of both in.dat and out.dat. The loop that actually does the copy should terminate on end of file.





I. Part One:


1 a)From engineering point-of-view 9bits = 1Byte, however, programmers have access to only 8bits in each byte. Hense, 1Byte = 8 bits .

b)1MB = 220B ~ 1,000,000B

c)Computers process data under the control of sets of instructions called computer programs/code.

d)Hardware(memory, CPU, drives, mouse, keyboard) & Software (compilers, OS, user programs, scripts)





2 a)editor.b)preprocessor.c)linker.d)loader.


3 a)main .b)Left brace ({),right brace (}).c)Semicolon.d)newline.e)if .


4 a)False.Comments do not cause any action to be performed when the program is executed.

They are used to document programs and improve their readability.




e)False.C++is case sensitive,so these variables are unique.



h)False.The operators *,/and %have the same precedence,and the operators +and -have

a lower precedence.

i)False.A single output statement using cout containing multiple \n escape sequences can

print several lines.


5 a)int c,thisIsAVariable,q76354,number;

b)std::cout <<"Enter an integer:";

c)std::cin >>age;

d)if (number !=7 )

std::cout <<"The variable number is not equal to 7 \n";

e)std::cout <<"This is a C++program \n";

f)std::cout <<"This is a C++\nprogram \n";

g)std::cout <<"This \nis \na \nC++\nprogram \n";

h)std::cout <<"This \tis \ta \tC++\tprogram \n";


6 a)//Calculate the product of three integers

b)int x,y,z,result;

c)cout <<"Enter three integers:";

d)cin >>x >>y >>z;

e)result =x *y *z;

f)cout <<"The product is "<<result <<endl;

g)return 0;


7 //Calculate the product of three integers

#include <iostream>

using std::cout;

using std::cin;

using std::endl;

int main()


int x,y,z,result;

cout <<"Enter three integers:";

cin >>x >>y >>z;

result =x *y *z;

cout <<"The product is "<<result <<endl;

return 0;



8 a)Error:Semicolon after the right parenthesis of the condition in the if statement.Correc-

tion:Remove the semicolon after the right parenthesis.Note:The result of this error is that

the output statement will be executed whether or not the condition in the if statement is true.

The semicolon after the right parenthesis is considered an empty statement —a statement that

does nothing.We will learn more about the empty statement in the next chapter.

b)Error:The relational operator =>.Correction:Change =>to >=.



II. Part Two:


1. Top down design is also called step-wise refinement. This is a plan of attack on the problem of designing an algorithm. Its essence is divide and conquer. The task at hand is divided into parts, or subtasks, each less complex than the original. These subtask is then subdivided into even smaller subtasks, and so forth. Eventually the subtasks become so small that they can be solved.


If the top-down structure in the design is preserved in the program, the program will be easier to understand, easier to debug, and easier to change when the need arises.



a) True, by dividing the program into high level components, top down design makes it possible to examine a program from an

abstract standpoint, thus enabling faster understanding by persons new to the code.

b) False, Top down design makes a program easier to change by isolating the effects of the change to the function being changed or to adjacent functions.

c) True, by separating the function, errors are isolated, making debugging easier.

d) True, by separating the function and isolating the effect of change, the changes necessary to maintenance are made easier.

e) True. Once the interface and a high level behavior of a part of a program is decided upon, a team member or a few team members can be assigned to carry out that portion of the program.


3. The program source code must #include <math.h>. This is the header file that contains the declarations (or prototypes) of the functions you wish to use.



a) False. In particular, math.h contains ONLY the declarations. A very few header files contain preprocessor macros directives that generate code in a program. (Templates, unknown to the student at this point require programs in the headers, (with some implementations) - but that is for the last chapter.)

b) True. The rest of the discussion is in part a).

c) True, for all implementations of which this writer is aware.

d) The answer depends on the compiler and linker ;you are using. Probably true for Unix like systems. This is false for systems such as Borland’s  `Example command: g++ file.cc -lm. In the Borland IDE, if a library is needed that is not in the 'standard' place, there are options in the IDE that can be changed.


5. The function sqrt, called in the body of the function root1, has no declaration (or prototype) given. The rest of the code is correct. The following preprocessor directive is needed prior to the definition of the function root to get a declaration of sqrt.


#include <math.h>


Some systems will create a declaration of an un-type-checked function, to allow the compiler to find other errors. The user is warned, but linking usually fails in this event.



a) There should be no white space before (or after) the file name.

b) The file name, iostream.h, should be all lower case.

c) Correct, excepting that the .h versions remain for backward compatibility. Use the header name without the .h and put in a using directive.

d) Correct, except that a using directive or qualification of identifiers is required.

e) The < > around the file name are missing. A few systems allow this. Actual error messages from the g++ compiler follow.


cd ~/AW/

g++ testInclude.cc

a) testInclude.cc:2: iostream.h: No such file or directory

b) testInclude.cc:3: Iostream.h: No such file or directory

c) is correct

d) is correct

e) testInclude.cc:6: `#include' expects "FILENAME" or <FILENAME>

Compilation exited abnormally with code 1 at Tue Jul 11 20:48:04


7. Note that using directive or qualification (such as std::cout, or std::pow(2,3))is necessary.

a) B cstdlib      e) C. cmath

b) C cmath        f) B cstdlib

c) A iostream     g) A iostream

d) C cmath



a) a. correct. power is assigned 2 to the exponent 3, i.e. 8.

b) incorrect, too many arguments for the pow function.

c) incorrect, attempts to assign the value of power to pow(base, exponent) which is not an lvalue, that is, it is not possible to assign

a value to this object.

d) correct. base is assigned 3 to the power 4, 81. Correctness does not depend on variable names. However, these are strange names for the arguments for the pow function. There is very likely an error in intent.


9. Values used for initialization are arbitrary except for obvious things, such as the sign of the argument for the sqrt must be nonnegative and the sign of the first argument (the base for the exponential) for the pow function cannot be negative unless the second argument is an integer.


a) //no include file necessary for this expression

  int y, x = 39; // any value for x

  y = x * x * x;

  //alternate solution using pow function.

  #include <cmath>

  using namespace std;

  y = pow(x, 3);


b) #include <cstdlib>

  using namespace std;


  int y; int x = -23; // any value for x

  y = abs(x);

  // or

  #include <math.h>

  double y, x = -79.8; // any value for y

  y = fabs(x);


c) #include <cmath>

  using namespace std;

  double z, x = 2.6;

  z = pow(x, 1.6);

d) #include <cmath>

  using namespace std;

  double z, area = 144; // here area must not be negative

  z = area * sqrt(area);

  // the pow function can be used for this:

  z = pow (area, 1.5);


e) // no includes are necessary here

  double p, x = 3, y = -4;

  //any values for x, y except x = y

  p = (x * x + y) / (x * x - y);

  //specifications can be interpreted to allow

  //int variables as well



a)  9/4 is 2, not the 2.25 that the programmer (evidently?) intended.

  double z = 2.25; or, if there is some good reason for 9/4 then write: double z = 9.0/4;

b) PI is an int, so 3.141... gets truncated to 3, which is stored as in

  double PI = 3.1415926; UNLESS the programmer really wants an int, then write int PI = 3;

c)  9/5 division is done as int divide, 9/5 is 1, and the assignment proceeds: F = C + 32.0;

We could use this:

    double(9)/5 * C + 32.0;

But this is may be better:

    F = 9.0/5 * C + 32.0;

An alternative is to do the division beforehand (9/5.0 = 1.8, or 9/5 = 1),but doing arithmetic is what we have computers for!

    F = 1.8 * C + 32.0;

d) Here the 9/5 is STILL integer division, so the discussion is as in c).


11.  The header is required for each answer.


   #include <math>

   using namespace std;

   double x, y, z;



   //round up

   z = ceil(x/y);



   // round down

   z = floor(x/y);



   //round nearest integer

   z = floor (x/y + 0.5);



a) rounds up to the next integer >= x/y

b) rounds to the integer nearest to x/y, exact 1/2 values round down

c) not reasonable. x/y with value 1.25 gives 0 result.

d) rounds to the integer nearest to x/y, exact 1/2 values round up

e) rounds down to the next integer <= x/y



//returns arithmetic mean of the arguments test1 through test4

double average_grade (double test1, double test2,

                           double test3, double test4);



// returns arithmetic mean of the arguments test1 through test4

double average_grade (double test1, double test2,

                             double test3, double test4)


    double average;

    average = (test1 + test2 + test3 + test4) / 4;

    return average;



This slightly more terse definition is sufficient:


//returns arithmetic mean of the arguments test1 through test4

double average_grade (double test1, double test2, double test3, double test4)


    return (test1 + test2 + test3 + test4) / 4;




return_type funct_name (parameter_list)


    //function body - compute return_value here

    return return_value;



Here parameter_list is a comma separated list of argument_type argument_name entries.



double x, y , z;

// code to fetch values for x and y

z = Sum(x, y);


17. A function definition is like a small program. Differences are that a program uses input, say cin, for input, or an fstream object, whereas a function uses parameters for inputs. Similarities are many. A program uses cout for output to the screen. A function can use cout to output to the screen. The function can return a value to the caller using a return statement. The program can, in fact, do this too, but such return values can only be success codes. The function and the program each have bodies of code that call other functions and do  computation to produce the values to satisfy specified. Each has local variables that are declared within the body. Finally, each can use global constants and variables (which are declared outside any function.)


18. The output is How, followed by a carriage return. The value of formal parameter first_par, 10, is greater than the value of formal parameter second_par, 9. Consequently, the condition is false, an "H" is returned to main. Output is "How" followed by a <CR> is sent to the screen.


19. number, type


20. The compiler complains about using a double for a parameter for a function calling for an integer parameter. The reason is the C++ strong type checking. There is a possible loss of information when a double is sent to any kind of integer (char, int, long) parameter, or assigned to an integer. Warning messages from the Gnu g++ compiler are:

 problem20.cc:14: warning: float or double used for argument 1


 double grade(int, int);


21. The prototype comment - that accompanies a function declaration (prototype) describes what a function returns and gives information needed by the user to call the function correctly.


22. A black box is a figure of speech that should convey the notion of a device whose use you know, but whose method or mode of operation you do not know. A well designed black box is frequently useful! If the programmer using a library black box knows the behavior and restrictions, use requires providing arguments in a call.


23. Procedural abstraction can be equated to writing and using functions as if they were black boxes. Another term that is used is functional abstraction. The function should be written (and documented) in such a way that the user does not have to peek inside to determine how to use that function. The notion of abstraction is intended to convey the idea that the details are not necessary to the use of the program. The definition (or prototype) comment should tell the programmer all conditions that are required of the

arguments for the function, and should describe the value that is  returned by the function when called with these arguments. Variables used in the function body should be declared in the function body. (Formal parameters must not be declared again because these are already declared in the function header.


24. False Only the client programmer should know the use to which a function is put. Only the author of the function should know the internals. The only thing these two share is the contract or specification of the function.


25. True. Under procedural abstraction, the author (or programmer) of a given function should know about how the application programmer (or the client) will use the function is the ‘contract.’ The contract is what the function is to do, and the conditions set on the parameters to guarantee that the function can do. The author should not know how the function is to be used by the client programmer. The client programmer should know only what the function does, the requirements on the parameters, but not how the

function carries out the task. This way each can do his job independently of the other.



a) Both author and client must know the requirements on the parameter values

b) Both client and author must know what the return value is to be,

c) Only the author should know the implementation details.

d) Only the client should know the details of the use to which the function is put.



a) too short, unlikely that x will tell what its value means.

b) like a,) xy is too short to be meaningful.

c) good. xylene_volume suggests the volume of a chemical named xylene

d) good. length suggests the use of the variable

e) jamesage ?? is this James' age? or Jame Sage? not very good because the meaning is unclear. Use either some capitalization scheme or underscores to clarify, as in jamesAge or james_age

f) good.velocity suggeses that the variable contains the value of a velocity tied to the problem.

g) good. acceleration suggests the value of some acceleration tied to the problem

h) u is too short to be clear.

i) position suggests a position connected to the problem.

j) cost_of_pizza, good, identifies clearly the variable's meaning.


28. d. All of these produce the same results. The denominator either already is double, or is converted to, double, so that all divisions are equivalent to that in part a), namely diameter/2.0. Reasoning follows:


a) The numerator is double, so that denominator 2 is converted to double, division is double

b) The numerator is double, and the cast double(2) makes

c) denominator double, so the division is double


29. With conditional clauses (if or if-else clauses) data should be constructed to guarantee that at the very least a path is followed with test data through every path through the code. For the code example, the following data gives 'complete coverage' of all possible branches through the code


case 1 x > y causes statement 1 to execute, in this case, the

             values of u, v are immaterial

case 2 x <= y and u > v causes statement 2 to execute

case 3 x <= y and u <= v causes statement 3 to execute


Note that the second if-else clause is encountered only where the first condition is false. Selecting data that gives 'complete coverage' is not easy. Commercial and free software packages exist that can ensure complete coverage.


30. These are accessible variables in these function(s)

a) x f, g, main

b) f f (recursively, see note below), g, main

c) y f only

d) z f only

e) w g, main

f) g g (recursively, see note below), main

g) u g, main

h) v g only

i) m main only

j) nn main only


Remarks: The student may not realize from the explicit statements in the text that a function may call itself recursively.


31. It is certainly possible to declare global variables, without the const modifier, allowing access by all functions defined in the file. However, this can make the program more complex, not less. Studies have shown that use of global variables can tie all the functions together in a way that makes the program harder to understand and harder to maintain. Global variables should be used only in programs where the last nanosecond of time is essential. Legacy code, code that is old, works well, but it is uneconomic to

rewrite, is a place where global variables may be necessary.


32. Similarity between local variables and parameters: both are variables that have scope within the function's block; Difference: the parameter is declared in the function header and is initialized by the calling process, the local variable is declared in the function's block and the programmer must initialize the variable.



III. Part Three:


1.Stream: Input is delivered to your program via C++ construct called a stream, output is delivered from you program to the output devices via a stream. C++ has input and output streams for both screen and keyboard, as well as file streams. This definition describes what a stream does, rather than telling what a stream is.


2. Object: An object is a variable that has value or values and has special purpose functions attached to the variable. Examples are cin, cout, and any file variables or other streams are examples of objects.

3. Both files and program variables store values and can have values retrieved from them.  Program variables exist only while the program runs while files can exist before a program is run, and can continue to exist after a program stops. Files are permanent, variables are not. Files provide the ability

to store large quantities of data whereas program variables do not provide quite so large a store.



 a) true.

 b) false, a program variable is not known outside the program

 c) true

 d) false, this is true only for a file

 e) false, the is true only of a file

 f) false, the is true only of a program variable.


5. The file variable must be declared to be one of the stream types we have seen: ifstream, ofstream, cin, or cout. Then the file must be connected to the file variable, using a member function open() whose argument is the name the file is know by external to the program.


  #include <fstream>

  using namespace std;

  // open a file named 'mydata.dat' for input:

  int length;

  ifstream mydata; // any legal C++ identifier works fine


  mydata >> length; // puts the int object from the file

  // mydata.dat into the int variable length.


6. The argument for the open member function should be "mydata.dat" - in quotes.


7. The argument for the open member function is a string, so should not be in quotes. This program will look for a file with an external name "myfile." It is unlikely to find such a file. Even if the program does find a file with this name, this is almost certainly an error.


8. False. The file, under its external name, must be connected using the open statement.  The file may not be referred to prior to the open statement, and it must be referred to by the program variable name, never the external file name.


9. True. The file has an external name and a stream name, known only to the program.

10. This is starting over. The file must be closed and opened again. This puts the read position at the start of the file, ready to be read again.


11. Among others, a stream has open, close, fail, good, EOF, width, precision, setf, get, put, and putback member functions. The following illustrates

the use of only a few of these.

   int c;

   ifstream in;

   ofstream out;






12. The << and >> symbols point in the direction the data is to be sent. Thus:

   cin >> x; // data flows FROM the input stream cin TO variable x

   cout << x; // data flows FROM x TO the output stream cout.


13. A class is a type whose variables are objects. The object's class determines which member functions the object has. Examples: ifstream, ofstream are classes that are declared in fstream, and defined in the fstreams library.


14. Calling_Object.Member_Function_Name(Argument_List); The usual rules for matching number and type of argument list to the parameter list apply.


15. Assuming that the file declarations are:

  #include <fstream> // for file operations.

  #include <cstdlib> // for exit

  using namespace std;

  //... what ever intervening code may be necessary

  ifstream in_stream;


  if (instream.fail())


    cout << "Cannot open Infile.dat. Exiting program" << endl;



  // ... proceed with file operations.


16. out_stream.close();


17. A file that is open will be automatically closed if the program terminates normally. There are no such assurances if the file terminates abnormally, perhaps due to an error.  If you close the file when you are finished with it, this potential for a problem is lessened. You may also wish to read the file

you have been writing. Then you must close the file, then connect it to an ifstream with the open statement. The file may be left in a corrupted state if it is not closed properly.


18. You need to replace out_stream with cout, and delete the open and close calls for out_stream. You do not need to declare cout, open cout, nor close cout. The #include <fstream> has all the iostream members you need for screen io. You also need to insert a using declaration.


19. You will need a using namespace std; statement.

  a) cstdlib

  b) either iostream or fstream

  c) cstdlib

  d) cctype

  e) cmath

  f) cmath

  g) either iostream or fstream

  h) cmath

  i) either iostream or fstream


20. char file_name[16];


21. The maximum number of characters that can be typed in for a string variable is one less than the declared size. Here the value is 20.



  a)ios::fixed Setting this bit causes floating point numbers not to be displayed in e-notation

  i.e. 'scientific notation.' Setting this unsets ios::scientific.

  b)ios::scientific Setting this bit causes floating point numbers to be displayed in

  e-notation i.e. 'scientific notation.' Setting this unsets ios::fixed.

  c) ios::showpoint Setting this bit causes the decimal point and trailing zeroes

  always to be displayed.

  d) ios::showpos Setting this bit causes a plus sign to be output before positive

  integer values.

  e) ios::right Setting this bit causes the next output to be placed at the right end of

  any field that is set with the width member function. That is, any extra blanks are put

  before the output. Setting this bit clears ios::left

  f) ios::left Setting this bit causes the next output to be placed at the left end of any

  field that is set with the width member function. That is, any extra blanks are put

  after the output. Setting this bit clears ios::right.


23. Under g++, output is the following, after embedding the code in a correct program:

  * 123*123*

  * 123*123*


24. Under g++, output is the following, after embedding the code in a correct program:

  * 123*123 * 123*


25. Under g++, output is the following, after embedding the code in a correct program:

  * 123*123*

  * +123*+123*

  *123 *


26. Under g++, output sent to out.dat is the following, after embedding the code in a correct program:

  * 123*123*

  * +123*+123*



27. The output stream ignores the setw or width setting. It takes whatever space it needs to output the data. setw or width() only has an effect if the width provided is greater than the data's width.


28. *123456* The output stream ignores setw when the data width is greater than the width provided in the argument to setw manipulator or the width member function.


29. Use of cout << setw(8) uses a manipulator that is not declared in iostream, but is declared in include iomanip. The member function cout.width(8) is already declared in iostream. There is no need to #include <iomanip> with the use of the member function. Manipulators are more convenient which is why they are provided.


30. Note: in.get() is used because it will do both of two necessary things: First, it will not ignore blanks. Second, it will return a 0 (false) when end of file is reached.

  // File: testp30.cc

  // test question: copy files: in.dat to out.dat check for

  // successful file opening, use EOF to terminate copy loop


  #include <fstream>

  #include <cstdlib> // for exit()

  using namespace std;


  int main()


    ifstream in;

    ofstream out;


    if ( in.bad())


      cout << "cannot open in.dat, aborting" << endl;




    if (out.bad())


      cout << "cannot open in.dat, aborting" << endl;



    char ch;

    while ( in.get(ch))

      out << ch;

    return 0;