CS201 Solved MCQs .../MCQsCS201Solve.pdf · By: Muhamamd Naveed MC090405686 15.1 Answer each of the...
-
Upload
nguyendang -
Category
Documents
-
view
239 -
download
3
Transcript of CS201 Solved MCQs .../MCQsCS201Solve.pdf · By: Muhamamd Naveed MC090405686 15.1 Answer each of the...
By:
Muhamamd Naveed
MC090405686
15.1
Answer each of the following:
a. Input/output in C++ occurs as ____________ of bytes.
b. The stream manipulators that format justification are_________,
_________ and _______.
c. Member function _________ can be used to set and reset format state.
d. Most C++ programs that do I/O should include the _________ header file
that contains the declarations required for all stream-I/O operations.
e. When using parameterized manipulators, the header file ____________
must be included.
f. Header file __________ contains the declarations required for user-
controlled file processing.
g. The ostream member function ___________ is used to perform
unformatted output.
h. Input operations are supported by class __________.
i. Outputs to the standard error stream are directed to either the
___________ or the ___________ stream object.
j. Output operations are supported by class ___________.
k. The symbol for the stream insertion operator is ____________.
l. The four objects that correspond to the standard devices on the system
include _________, _________, __________ and ___________.
[Page 805]
m. The symbol for the stream extraction operator is __________.
n. The stream manipulators ___________, __________ and ___________
specify that integers should be displayed in octal, hexadecimal and
decimal formats, respectively.
o. When used, the _________ stream manipulator causes positive numbers
to display with a plus sign.
15.2 State whether the following are true or false. If the answer is false, explain why.
a. The stream member function flags with a long argument sets the flags
state variable to its argument and returns its previous value.
b. The stream insertion operator << and the stream-extraction operator >> are
overloaded to handle all standard data typesincluding strings and memory
addresses (stream-insertion only)and all user-defined data types.
c. The stream member function flags with no arguments resets the stream's
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
format state.
d. The stream extraction operator >> can be overloaded with an operator
function that takes an istream reference and a reference to a user-defined
type as arguments and returns an istream reference.
e. The stream insertion operator << can be overloaded with an operator
function that takes an istream reference and a reference to a user-defined
type as arguments and returns an istream reference.
f. Input with the stream extraction operator >> always skips leading white-
space characters in the input stream, by default.
g. The stream member function rdstate returns the current state of the
stream.
h. The cout stream normally is connected to the display screen.
i. The stream member function good returns TRue if the bad, fail and eof
member functions all return false.
j. The cin stream normally is connected to the display screen.
k. If a nonrecoverable error occurs during a stream operation, the bad
member function will return TRue.
l. Output to cerr is unbuffered and output to clog is buffered.
m. Stream manipulator showpoint forces floating-point values to print with
the default six digits of precision unless the precision value has been
changed, in which case floating-point values print with the specified
precision.
n. The ostream member function put outputs the specified number of
characters.
o. The stream manipulators dec, oct and hex affect only the next integer
output operation.
p. By default, memory addresses are displayed as long integers.
15.3 For each of the following, write a single statement that performs the indicated
task.
a. Output the string "Enter your name: ".
b. Use a stream manipulator that causes the exponent in scientific notation
and the letters in hexadecimal values to print in capital letters.
c. Output the address of the variable myString of type char *.
d. Use a stream manipulator to ensure floating-point values print in scientific
notation.
e. Output the address in variable integerPtr of type int *.
f. Use a stream manipulator such that, when integer values are output, the
integer base for octal and hexadecimal values is displayed.
g. Output the value pointed to by floatPtr of type float *.
h. Use a stream member function to set the fill character to '*' for printing
in field widths larger than the values being output. Write a separate
statement to do this with a stream manipulator.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
i. Output the characters '0' and 'K' in one statement with ostream
function put.
j. Get the value of the next character in the input stream without extracting it
from the stream.
[Page 806]
k. Input a single character into variable charValue of type char, using the
istream member function get in two different ways.
l. Input and discard the next six characters in the input stream.
m. Use istream member function read to input 50 characters into char
array line.
n. Read 10 characters into character array name. Stop reading characters if
the '.' delimiter is encountered. Do not remove the delimiter from the
input stream. Write another statement that performs this task and removes
the delimiter from the input.
o. Use the istream member function gcount to determine the number of
characters input into character array line by the last call to istream
member function read, and output that number of characters, using
ostream member function write.
p. Output the following values: 124, 18.376, 'Z', 1000000 and "String".
q. Print the current precision setting, using a member function of object
cout.
r. Input an integer value into int variable months and a floating-point value
into float variable percentageRate.
s. Print 1.92, 1.925 and 1.9258 separated by tabs and with 3 digits of
precision, using a manipulator.
t. Print integer 100 in octal, hexadecimal and decimal, using stream
manipulators.
u. Print integer 100 in decimal, octal and hexadecimal, using a stream
manipulator to change the base.
v. Print 1234 right justified in a 10-digit field.
w. Read characters into character array line until the character 'z' is
encountered, up to a limit of 20 characters (including a terminating null
character). Do not extract the delimiter character from the stream.
x. Use integer variables x and y to specify the field width and precision used
to display the double value 87.4573, and display the value.
15.4 Identify the error in each of the following statements and explain how to correct
it.
a. cout << "Value of x <= y is: " << x <= y;
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
b.
c. The following statement should print the integer value of 'c'. d. cout << 'c'; e. cout << ""A string in quotes"";
f.
15.5 For each of the following, show the output.
a. cout << "12345" << endl; b. cout.width( 5 ); c. cout.fill( '*' ); d. cout << 123 << endl << 123;
e. f. cout << setw( 10 ) << setfill( '$' ) << 10000;
g. h. cout << setw( 8 ) << setprecision( 3 ) << 1024.987654;
i. j. cout << showbase << oct << 99 << endl << hex << 99;
k. l. cout << 100000 << endl << showpos << 100000;
m. n. cout << setw( 10 ) << setprecision( 2 ) << scientific <<
444.93738;
o.
Answers to Self-Review Exercises
15.1 a) streams. b) left, right and internal. c) flags. d) <iostream>. e)
<iomanip>. f) <fstream>. g) write. h) istream. i) cerr or clog. j) ostream. k)
<<. l) cin, cout, cerr and clog. m) >>. n) oct, hex and dec. o) showpos.
15.2 a) False. The stream member function flags with a fmtflags argument sets the
flags state variable to its argument and returns the prior state settings. b) False.
The stream insertion and stream extraction operators are not overloaded for all
user-defined types. The programmer of a class must specifically provide the
overloaded operator functions to overload the stream operators for use with each
user-defined type. c) False. The stream member function flags with no
arguments returns the current format settings as a fmtflags data type, which
represents the format state. d) True. e) False. To overload the stream insertion
operator <<, the overloaded operator function must take an ostream reference
and a reference to a user-defined type as arguments and return an ostream
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
reference. f) True. g) True. h) True. i) True. j) False. The cin stream is connected
to the standard input of the computer, which normally is the keyboard. k) True. l)
True. m) True. n) False. The ostream member function put outputs its single-
character argument. o) False. The stream manipulators dec, oct and hex set the
output format state for integers to the specified base until the base is changed
again or the program terminates. p) False. Memory addresses are displayed in
hexadecimal format by default. To display addresses as long integers, the address
must be cast to a long value.
15.3 a. cout << "Enter your name: ";
b. c. cout << uppercase;
d. e. cout << static_cast< void * >( myString );
f. g. cout << scientific;
h. i. cout << integerPtr;
j. k. cout << showbase;
l. m. cout << *floatPtr;
n. o. cout.fill( '*' ); p. cout << setfill( '*' );
q. r. cout.put( '0' ).put( 'K' );
s. t. cin.peek();
u. v. charValue = cin.get(); w. cin.get( charValue );
x. y. cin.ignore( 6 );
z. aa. cin.read( line, 50 );
bb. cc. cin.get( name, 10, '.' ); dd. cin.getline( name, 10, '.' );
ee. ff. cout.write( line, cin.gcount() );
gg. hh. cout << 124 << ' ' << 18.376 << ' ' << "Z" << 1000000 <<
"String";
ii. jj. cout << cout.precision();
kk.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
ll. cin >> months >> percentageRate;
mm. nn. cout << setprecision( 3 ) << 1.92 << '\t' << 1.925 << '\t'
<< 1.9258;
oo. pp. cout << oct << 100 << '\t' << hex << 100 << '\t' << dec <<
100;
qq. rr. cout << 100 << '\t' << setbase( 8 ) << 100 << '\t' <<
setbase( 16 ) << 100;
ss. tt. cout << setw( 10 ) << 1234;
uu. vv. cin.get( line, 20, 'z' );
ww. xx. cout << setw( x ) << setprecision( y ) << 87.4573;
yy.
15.4 a. Error: The precedence of the << operator is higher than that of <=, which
causes the statement to be evaluated improperly and also causes a
compiler error.
Correction: To correct the statement, place parentheses around the
expression x <= y. This problem will occur with any expression that uses
operators of lower precedence than the << operator if the expression is not
placed in parentheses.
b. Error: In C++, characters are not treated as small integers, as they are in
C.
Correction: To print the numerical value for a character in the computer's
character set, the character must be cast to an integer value, as in the
following:
cout << static_cast< int >( 'c' );
c. Error: Quote characters cannot be printed in a string unless an escape
sequence is used.
Correction: Print the string in one of the following ways:
cout << '"' << "A string in quotes" << '"'; cout << "\"A string in quotes\"";
15.5 a. 12345 b. **123
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
c. 123
d. e. $$$$$10000
f. g. 1024.988
h. i. 0143 j. 0x63
k. l. 100000 m. +100000
n. o. 4.45e+002
p.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
Self-Review Exercises
17.1 Fill in the blanks in each of the following:
a. Ultimately, all data items processed by a computer are reduced to combinations
of__________and__________.
b. The smallest data item a computer can process is called a__________.
c. A(n)__________is a group of related records.
d. Digits, letters and special symbols are referred to as__________.
e. A group of related files is called a(n)__________.
f. Member function__________of the file streams fstream, ifstream and
ofstream closes a file.
g. The istream member function__________reads a character from the specified
stream.
h. Member function__________of the file streams fstream, ifstream and
ofstream opens a file.
i. The istream member function__________is normally used when reading data
from a file in random-access applications.
j. Member functions__________and__________of istream and ostream, set
the file-position pointer to a specific location in an input or output stream,
respectively.
17.2 State which of the following are true and which are false. If false, explain why.
a. Member function read cannot be used to read data from the input object cin.
b. The programmer must create the cin, cout, cerr and clog objects explicitly.
c. A program must call function close explicitly to close a file associated with an
ifstream, ofstream or fstream object.
[Page 877]
d. If the file-position pointer points to a location in a sequential file other than the
beginning of the file, the file must be closed and reopened to read from the
beginning of the file.
e. The ostream member function write can write to standard-output stream
cout.
f. Data in sequential files always is updated without overwriting nearby data.
g. Searching all records in a random-access file to find a specific record is
unnecessary.
h. Records in random-access files must be of uniform length.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
i. Member functions seekp and seekg must seek relative to the beginning of a
file.
17.3 Assume that each of the following statements applies to the same program.
a. Write a statement that opens file oldmast.dat for input; use an ifstream
object called inOldMaster.
b. Write a statement that opens file trans.dat for input; use an ifstream object
called inTransaction.
c. Write a statement that opens file newmast.dat for output (and creation); use
ofstream object outNewMaster.
d. Write a statement that reads a record from the file oldmast.dat. The record
consists of integer accountNumber, string name and floating-point
currentBalance; use ifstream object inOldMaster.
e. Write a statement that reads a record from the file TRans.dat. The record
consists of integer accountNum and floating-point dollarAmount; use
ifstream object inTransaction.
f. Write a statement that writes a record to the file newmast.dat. The record
consists of integer accountNum, string name, and floating-point
currentBalance; use ofstream object outNewMaster.
17.4 Find the error(s) and show how to correct it (them) in each of the following.
a. File payables.dat referred to by ofstream object outPayable has not been
opened. b. outPayable << account << company << amount << endl;
c. The following statement should read a record from the file payables.dat. The
ifstream object inPayable refers to this file, and istream object
inReceivable refers to the file receivables.dat. d. inReceivable >> account >> company >> amount;
e. The file tools.dat should be opened to add data to the file without discarding
the current data. f. ofstream outTools( "tools.dat", ios::out );
Self-Review Exercises
18.1 Fill in the blanks in each of the following:
a. Header ___________ must be included for class string.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
b. Class string belongs to the ______________ namespace.
c. Function ___________ deletes characters from a string.
d. Function ___________ finds the first occurrence of any character from a
string.
18.2 State which of the following statements are true and which are false. If a
statement is false, explain why.
a. Concatenation of string objects can be performed with the addition
assignment operator, +=.
b. Characters within a string begin at index 0.
c. The assignment operator, =, copies a string.
d. A C-style string is a string object.
18.3 Find the error(s) in each of the following, and explain how to correct it (them):
a. string string1( 28 ); // construct string1 b. string string2( 'z' ); // construct string2
c. d. // assume std namespace is known e. const char *ptr = name.data(); // name is "joe bob" f. ptr[ 3 ] = '-'; g. cout << ptr << endl;
Answers to Self-Review Exercises
18.1 a)<string>. b) std. c) erase. d) find_first_of.
18.2 a. True.
b. True.
c. True.
d. False. A string is an object that provides many different
services. A C-style string does not provide any services. C-
style strings are null terminated; strings are not
necessarily null terminated. C-style strings are pointers and
strings are not.
18.3 a. Constructors for class string do not exist for integer and
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
character arguments. Other valid constructors should be
usedconverting the arguments to strings if need be.
b. Function data does not add a null terminator. Also, the
code attempts to modify a const char. Replace all of the
lines with the code: c. cout << name.substr( 0, 3 ) + "-" +
name.substr( 4 ) << endl;
Answers to Self-Review Exercises
17.1 a) 1s, 0s. b) bit. c) file. d) characters. e) database. f) close. g) get. h) open. i) read. j)
seekg, seekp.
17.2 a. False. Function read can read from any input stream object derived from
istream.
b. False. These four streams are created automatically for the programmer. The
<iostream> header must be included in a file to use them. This header
includes declarations for each stream object.
c. False. The files will be closed when destructors for ifstream, ofstream or
fstream objects execute when the stream objects go out of scope or before
program execution terminates, but it is a good programming practice to close
all files explicitly with close once they are no longer needed.
d. False. Member function seekp or seekg can be used to reposition the put or
get fileposition pointer to the beginning of the file.
[Page 878]
e. True.
f. False. In most cases, sequential file records are not of uniform length.
Therefore, it is possible that updating a record will cause other data to be
overwritten.
g. True.
h. False. Records in a random-access file normally are of uniform length.
i. False. It is possible to seek from the beginning of the file, from the end of the
file and from the current position in the file.
17.3 a. ifstream inOldMaster( "oldmast.dat", ios::in ); b. ifstream inTransaction( "trans.dat", ios::in );
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
c. ofstream outNewMaster( "newmast.dat", ios::out); d. inOldMaster >> accountNumber >> name >> currentBalance; e. inTransaction >> accountNum >> dollarAmount; f. outNewMaster << accountNum << name << currentBalance;
17.4 a. Error: The file payables.dat has not been opened before the attempt is made
to output data to the stream.
Correction: Use ostream function open to open payables.dat for output.
b. Error: The incorrect istream object is being used to read a record from the file
named payables.dat.
Correction: Use istream object inPayable to refer to payables.dat.
c. Error: The file's contents are discarded because the file is opened for output
(ios::out).
Correction: To add data to the file, open the file either for updating (ios::ate)
or for appending
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
Self-Review Exercises
3.1 Fill in the blanks in each of the following:
a. A house is to a blueprint as a(n) _________ is to a class.
b. Every class definition contains keyword _________ followed immediately by
the class's name.
c. A class definition is typically stored in a file with the _________ filename
extension.
d. Each parameter in a function header should specify both a(n) _________ and
a(n) _________.
e. When each object of a class maintains its own copy of an attribute, the variable
that represents the attribute is also known as a(n) _________.
f. Keyword public is a(n) _________.
g. Return type _________ indicates that a function will perform a task but will
not return any information when it completes its task.
h. Function _________ from the <string> library reads characters until a
newline character is encountered, then copies those characters into the
specified string.
[Page 122]
i. When a member function is defined outside the class definition, the function
header must include the class name and the _________, followed by the
function name to "tie" the member function to the class definition.
j. The source-code file and any other files that use a class can include the class's
header file via an _________ preprocessor directive.
3.2 State whether each of the following is true or false. If false, explain why.
a. By convention, function names begin with a capital letter and all subsequent
words in the name begin with a capital letter.
b. Empty parentheses following a function name in a function prototype indicate
that the function does not require any parameters to perform its task.
c. Data members or member functions declared with access specifier private are
accessible to member functions of the class in which they are declared.
d. Variables declared in the body of a particular member function are known as
data members and can be used in all member functions of the class.
e. Every function's body is delimited by left and right braces ({ and }).
f. Any source-code file that contains int main() can be used to execute a
program.
g. The types of arguments in a function call must match the types of the
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
corresponding parameters in the function prototype's parameter list.
3.3 What is the difference between a local variable and a data member?
3.4 Explain the purpose of a function parameter. What is the difference between a
parameter and an argument?
Answers to Self-Review Exercises
3.1 a) object. b) class. c) .h d) type, name. e) data member. f) access specifier. g) void.
h) getline. i) binary scope resolution operator (::). j) #include.
3.2 a) False. By convention, function names begin with a lowercase letter and all
subsequent words in the name begin with a capital letter. b) True. c) True. d) False.
Such variables are called local variables and can be used only in the member function
in which they are declared. e) True. f) True. g) True.
3.3 A local variable is declared in the body of a function and can be used only from the
point at which it is declared to the immediately following closing brace. A data
member is declared in a class definition, but not in the body of any of the class's
member functions. Every object (instance) of a class has a separate copy of the class's
data members. Also, data members are accessible to all member functions of the class.
3.4 A parameter represents additional information that a function requires to perform its
task. Each parameter required by a function is specified in the function header. An
argument is the value supplied in the function call. When the function is called, the
argument value is passed into the function parameter so that the function can perform
its task.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
Self-Review Exercises
6.1 Answer each of the following:
a. Program components in C++ are called ________ and ________.
b. A function is invoked with a(n) ________.
c. A variable that is known only within the function in which it is defined is
called a(n) ________.
d. The ________ statement in a called function passes the value of an
expression back to the calling function.
e. The keyword ________ is used in a function header to indicate that a
function does not return a value or to indicate that a function contains no
parameters.
f. The ________ of an identifier is the portion of the program in which the
identifier can be used.
g. The three ways to return control from a called function to a caller are
________, ________ and ________.
h. A(n)________ allows the compiler to check the number, types and order
of the arguments passed to a function.
i. Function ________ is used to produce random numbers.
j. Function ________ is used to set the random number seed to randomize a
program.
k. The storage-class specifiers are mutable, ________, ________, ________
and ________.
l. Variables declared in a block or in the parameter list of a function are
assumed to be of storage class ________ unless specified otherwise.
m. Storage-class specifier ________ is a recommendation to the compiler to
store a variable in one of the computer's registers.
n. A variable declared outside any block or function is a(n) ________
variable.
o. For a local variable in a function to retain its value between calls to the
function, it must be declared with the ________ storage-class specifier.
p. The six possible scopes of an identifier are ________, ________,
________, ________, ________ and ________.
q. A function that calls itself either directly or indirectly (i.e., through
another function) is a(n) ________ function.
r. A recursive function typically has two components: One that provides a
means for the recursion to terminate by testing for a(n) ________ case and
one that expresses the problem as a recursive call for a slightly simpler
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
problem than the original call.
s. In C++, it is possible to have various functions with the same name that
operate on different types or numbers of arguments. This is called
function ________.
t. The ________ enables access to a global variable with the same name as a
variable in the current scope.
u. The ________ qualifier is used to declare read-only variables.
v. A function ________ enables a single function to be defined to perform a
task on many different data types.
6.2 For the program in Fig. 6.40, state the scope (either function scope, file scope,
block scope or function-prototype scope) of each of the following elements:
a. The variable x in main.
b. The variable y in cube.
c. The function cube.
d. The function main.
e. The function prototype for cube.
f. The identifier y in the function prototype for cube.
Figure 6.40. Program for Exercise 6.2
(This item is displayed on page 312 in the print version)
1 // Exercise 6.2: Ex06_02.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 int cube( int y ); // function prototype 7 8 int main() 9 { 10 int x; 11 12 for ( x = 1; x <= 10; x++ ) // loop 10 times 13 cout << cube( x ) << endl; // calculate cube of x and output results 14 15 return 0; // indicates successful termination 16 } // end main 17 18 // definition of function cube 19 int cube( int y ) 20 { 21 return y * y * y; 22 } // end function cube
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
6.3 Write a program that tests whether the examples of the math library function calls
shown in Fig. 6.2 actually produce the indicated results.
6.4 Give the function header for each of the following functions:
a. Function hypotenuse that takes two double-precision, floating-point
arguments, side1 and side2, and returns a double-precision, floating-
point result.
b. Function smallest that takes three integers, x, y and z, and returns an
integer.
c. Function instructions that does not receive any arguments and does not
return a value. [Note: Such functions are commonly used to display
instructions to a user.]
d. Function intToDouble that takes an integer argument, number, and
returns a double-precision, floating-point result.
6.5 Give the function prototype for each of the following:
a. The function described in Exercise 6.4(a).
b. The function described in Exercise 6.4(b).
c. The function described in Exercise 6.4(c).
d. The function described in Exercise 6.4(d).
6.6 Write a declaration for each of the following:
a. Integer count that should be maintained in a register. Initialize count to
0.
b. Double-precision, floating-point variable lastVal that is to retain its
value between calls to the function in which it is defined.
6.7 Find the error in each of the following program segments, and explain how the
error can be corrected (see also Exercise 6.53):
a. int g( void ) b. { c. cout << "Inside function g" << endl; d. int h( void )
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
e. { f. cout << "Inside function h" << endl; g. } h. }
i.
j. int sum( int x, int y ) k. { l. int result; m. n. o. result = x + y; p. }
q.
r. int sum( int n ) s. { t. if ( n == 0 ) u. return 0; v. else w. n + sum( n - 1 ); x. }
y.
z. void f ( double a); aa. { bb. float a; cc. cout << a << endl; dd. }
ee.
ff. void product( void ) gg. { hh. int a; ii. int b; jj. int c; kk. int result; ll. cout << "Enter three integers: "; mm. cin >> a >> b >> c; nn. result = a * b * c; oo. cout << "Result is " << result; pp. return result; qq. }
rr.
6.8 Why would a function prototype contain a parameter type declaration such as double &?
6.9 (True/False) All arguments to function calls in C++ are passed by value.
6.10 Write a complete program that prompts the user for the radius of a sphere, and
calculates and prints the volume of that sphere. Use an inline function
sphereVolume that returns the result of the following expression: ( 4.0 / 3.0 ) *
3.14159 * pow( radius, 3 ).
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
Answers to Self-Review Exercises
6.1 a) functions, classes. b) function call. c) local variable. d) return. e)
void. f) scope. g) return;, return expression; or encounter the closing
right brace of a function. h) function prototype. i) rand. j) srand. k)
auto, register, extern, static. l) auto. m) register. n) global. o)
static. p) function scope, file scope, block scope, function-prototype
scope, class scope, namespace scope. q) recursive. r) base. s)
overloading. t) unary scope resolution operator (::). u) const. v)
template.
6.2 a) block scope. b) block scope. c) file scope. d) file scope. e) file scope.
f) function-prototype scope.
6.3 See the following program:
1 // Exercise 6.3: Ex06_03.cpp 2 // Testing the math library functions. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 using std::fixed; 7 8 #include <iomanip> 9 using std::setprecision; 10 11 #include <cmath> 12 using namespace std; 13 14 int main() 15 { 16 cout << fixed << setprecision( 1 ); 17 18 cout << "sqrt(" << 900.0 << ") = " << sqrt( 900.0 ) 19 << "\nsqrt(" << 9.0 << ") = " << sqrt( 9.0 ); 20 cout << "\nexp(" << 1.0 << ") = " << setprecision( 6 ) 21 << exp( 1.0 ) << "\nexp(" << setprecision( 1 ) << 2.0 22 << ") = " << setprecision( 6 ) << exp( 2.0 ); 23 cout << "\nlog(" << 2.718282 << ") = " << setprecision( 1 )
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
24 << log( 2.718282 ) 25 << "\nlog(" << setprecision( 6 ) << 7.389056 << ") = " 26 << setprecision( 1 ) << log( 7.389056 ); 27 cout << "\nlog10(" << 1.0 << ") = " << log10( 1.0 ) 28 << "\nlog10(" << 10.0 << ") = " << log10( 10.0 ) 29 << "\nlog10(" << 100.0 << ") = " << log10( 100.0 ); 30 cout << "\nfabs(" << 13.5 << ") = " << fabs( 13.5 ) 31 << "\nfabs(" << 0.0 << ") = " << fabs( 0.0 ) 32 << "\nfabs(" << -13.5 << ") = " << fabs( -13.5 ); 33 cout << "\nceil(" << 9.2 << ") = " << ceil( 9.2 ) 34 << "\nceil(" << -9.8 << ") = " << ceil( -9.8 ); 35 cout << "\nfloor(" << 9.2 << ") = " << floor( 9.2 ) 36 << "\nfloor(" << -9.8 << ") = " << floor( -9.8 ); 37 cout << "\npow(" << 2.0 << ", " << 7.0 << ") = " 38 << pow( 2.0, 7.0 ) << "\npow(" << 9.0 << ", " 39 << 0.5 << ") = " << pow( 9.0, 0.5 ); 40 cout << setprecision(3) << "\nfmod(" 41 << 13.675 << ", " << 2.333 << ") = " 42 << fmod( 13.675, 2.333) << setprecision( 1 ); 43 cout << "\nsin(" << 0.0 << ") = " << sin( 0.0 ); 44 cout << "\ncos(" << 0.0 << ") = " << cos( 0.0 ); 45 cout << "\ntan(" << 0.0 << ") = " << tan( 0.0 ) << endl; 46 return 0; // indicates successful termination 47 } // end main
sqrt(900.0) = 30.0 sqrt(9.0) = 3.0 exp(1.0) = 2.718282 exp(2.0) = 7.389056 log(2.718282) = 1.0 log(7.389056) = 2.0 log10(1.0) = 0.0 log10(10.0) = 1.0 log10(100.0) = 2.0 fabs(13.5) = 13.5 fabs(0.0) = 0.0 fabs(-13.5) = 13.5 ceil(9.2) = 10.0 ceil(-9.8) = -9.0 floor(9.2) = 9.0 floor(-9.8) = -10.0 pow(2.0, 7.0) = 128.0 pow(9.0, 0.5) = 3.0 fmod(13.675, 2.333) = 2.010 sin(0.0) = 0.0 cos(0.0) = 1.0 tan(0.0) = 0.0
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
6.4 a. double hypotenuse( double side1, double side2 )
b. int smallest( int x, int y, int z )
c. void instructions( void ) // in C++ (void) can be written ()
d. double intToDouble( int number )
6.5 a. double hypotenuse( double, double );
b. int smallest( int, int, int );
c. void instructions( void ); // in C++ (void) can be written ()
d. double intToDouble( int );
6.6 a. register int count = 0;
b. static double lastVal;
6.7 a. Error: Function h is defined in function g.
Correction: Move the definition of h out of the definition of g.
b. Error: The function is supposed to return an integer, but does
not.
Correction: Delete variable result and place the following
statement in the function:
return x + y;
c. Error: The result of n + sum( n - 1 ) is not returned; sum
returns an improper result.
Correction: Rewrite the statement in the else clause as
return n + sum( n - 1 );
d. Errors: Semicolon after the right parenthesis that encloses the
parameter list, and redefining the parameter a in the function
definition.
Corrections: Delete the semicolon after the right parenthesis of
the parameter list, and delete the declaration float a;.
e. Error: The function returns a value when it is not supposed to.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
Correction: Eliminate the return statement.
6.8 This creates a reference parameter of type "reference to double" that
enables the function to modify the original variable in the calling
function.
6.9 False. C++ enables pass-by-reference using reference parameters (and
pointers, as we discuss in Chapter 8).
6.10 See the following program:
1 // Exercise 6.10 Solution: Ex06_10.cpp 2 // Inline function that calculates the volume of a sphere. 3 #include <iostream> 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 8 #include <cmath> 9 using std::pow; 10 11 const double PI = 3.14159; // define global constant PI 12 13 // calculates volume of a sphere 14 inline double sphereVolume( const double radius ) 15 { 16 return 4.0 / 3.0 * PI * pow( radius, 3 ); 17 } // end inline function sphereVolume 18 19 int main() 20 { 21 double radiusValue; 22 23 // prompt user for radius 24 cout << "Enter the length of the radius of your sphere: "; 25 cin >> radiusValue; // input radius 26 27 // use radiusValue to calculate volume of sphere and display result 28 cout << "Volume of sphere with radius " << radiusValue 29 << " is " << sphereVolume( radiusValue ) << endl; 30 return 0; // indicates successful termination 31 } // end main
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
Self-Review Exercises
7.1 Answer each of the following:
a. Lists and tables of values can be stored in __________ or __________.
b. The elements of an array are related by the fact that they have the same
________ and ___________.
c. The number used to refer to a particular element of an array is called its
________.
d. A(n) __________ should be used to declare the size of an array, because it
makes the program more scalable.
e. The process of placing the elements of an array in order is called
________ the array.
f. The process of determining if an array contains a particular key value is
called _________ the array.
g. An array that uses two subscripts is referred to as a(n) _________ array.
7.2 State whether the following are true or false. If the answer is false, explain why.
a. An array can store many different types of values.
b. An array subscript should normally be of data type float.
c. If there are fewer initializers in an initializer list than the number of
elements in the array, the remaining elements are initialized to the last
value in the initializer list.
d. It is an error if an initializer list contains more initializers than there are
elements in the array.
e. An individual array element that is passed to a function and modified in
that function will contain the modified value when the called function
completes execution.
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
7.3 Write one or more statements that perform the following tasks for and array
called fractions:
a. Define a constant variable arraySize initialized to 10.
b. Declare an array with arraySize elements of type double, and initialize
the elements to 0.
c. Name the fourth element of the array.
d. Refer to array element 4.
e. Assign the value 1.667 to array element 9.
f. Assign the value 3.333 to the seventh element of the array.
g. Print array elements 6 and 9 with two digits of precision to the right of the
decimal point, and show the output that is actually displayed on the
screen.
h. Print all the array elements using a for statement. Define the integer
variable i as a control variable for the loop. Show the output.
7.4 Answer the following questions regarding an array called table:
a. Declare the array to be an integer array and to have 3 rows and 3 columns.
Assume that the constant variable arraySize has been defined to be 3.
b. How many elements does the array contain?
c. Use a for repetition statement to initialize each element of the array to the
sum of its subscripts. Assume that the integer variables i and j are
declared as control variables.
d. Write a program segment to print the values of each element of array
table in tabular format with 3 rows and 3 columns. Assume that the array
was initialized with the declaration e. int table[ arraySize ][ arraySize ] = { { 1, 8 }, { 2, 4, 6
}, { 5 } };
and the integer variables i and j are declared as control variables. Show
the output.
7.5 Find the error in each of the following program segments and correct the error:
a. #include <iostream>;
b. arraySize = 10; // arraySize was declared const
c. Assume that int b[ 10 ] = { 0 }; d. for ( int i = 0; <= 10; i++ ) e. b[ i ] = 1;
f. Assume that int a[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
g. a[ 1, 1 ] = 5;
Answers to Self-Review Exercises
7.1 a) arrays, vectors. b) name, type. c) subscript (or index). d) constant variable. e)
sorting. f) searching. g) two-dimensional.
7.2 a. False. An array can store only values of the same type.
b. False. An array subscript should be an integer or an integer expression.
c. False. The remaining elements are initialized to zero.
d. True.
e. False. Individual elements of an array are passed by value. If the entire
array is passed to a function, then any modifications will be reflected in
the original.
7.3 a. const int arraySize = 10;
b. double fractions[ arraySize ] = { 0.0 };
c. fractions[ 3 ]
d. fractions[ 4 ]
e. fractions[ 9 ] = 1.667;
f. fractions[ 6 ] = 3.333; g. cout << fixed << setprecision ( 2 ); h. cout << fractions[ 6 ] < < ' ' fractions[ 9 ] << endl;
i. Output: 3.33 1.67. j. for ( int i = 0; < arraySize; i++ ) k. cout << "fractions[" < i << "] = " << fractions[ i ] <<
endl;
l.
[Page 390]
Output:
fractions[ 0 ] = 0.0 fractions[ 1 ] = 0.0 fractions[ 2 ] = 0.0 fractions[ 3 ] = 0.0 fractions[ 4 ] = 0.0 fractions[ 5 ] = 0.0 fractions[ 6 ] = 3.333
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com
By:
Muhamamd Naveed
MC090405686
fractions[ 7 ] = 0.0 fractions[ 8 ] = 0.0 fractions[ 9 ] = 1.667
7.4 a. int table[ arraySize ][ arraySize ];
b. Nine. c. for ( i = 0; i < arraySize; i++ ) d. e. for ( j = 0; j < arraySize; j++ ) f. table[ i ][ j ] = i + j;
g. h. cout << " [0] [1] [2]" << endl; i. j. for ( int i = 0; i < arraySize; i++ ) { k. cout << '[' << i << "] "; l. m. for ( int j = 0; j < arraySize; j++ ) n. cout << setw( 3 ) << table[ i ][ j ] << " "; o. p. cout << endl;
q. Output: r. [0] [1] [2] s. [0] 1 8 0 t. [1] 2 4 6 u. [2] 5 0 0
7.5 a. Error: Semicolon at end of #include preprocessor directive.
Correction: Eliminate semicolon.
b. Error: Assigning a value to a constant variable using an assignment
statement.
Correction: Initialize the constant variable in a const int arraySize
declaration.
c. Error: Referencing an array element outside the bounds of the array
(b[10]).
Correction: Change the final value of the control variable to 9.
d. Error: Array subscripting done incorrectly.
Correction: Change the statement to a[ 1 ][ 1 ] = 5;
CS201 Solved MCQshttp://vustudents.ning.com
http://vustudents.ning.com