CS201 Solved MCQs.

Similar documents
Chapter 12 - C++ Stream Input/Output

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

I/O Streams and Standard I/O Devices (cont d.)

CS2141 Software Development using C/C++ Stream I/O

Chapter 21 - C++ Stream Input/Output

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 21 - C++ Stream Input/Output

Chapter 3 - Notes Input/Output

Streams - Object input and output in C++

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

BITG 1233: Introduction to C++

Introduction to C++ (Extensions to C)

Objects and streams and files CS427: Elements of Software Engineering

The C++ Language. Arizona State University 1

UEE1303(1070) S 12 Object-Oriented Programming in C++

C++ Programming Lecture 10 File Processing

Introduction to C++ Systems Programming

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

C++ Input/Output: Streams

Chapter 15 - C++ As A "Better C"

Week 3: File I/O and Formatting 3.7 Formatting Output

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

CS201 Latest Solved MCQs

Module 11 The C++ I/O System

C++ does not, as a part of the language, define how data are sent out and read into the program

Lecture 9. Introduction

Software Design & Programming I

CS3157: Advanced Programming. Outline

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Fig: iostream class hierarchy

IS 0020 Program Design and Software Tools

Getting started with C++ (Part 2)

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

We will exclusively use streams for input and output of data. Intro Programming in C++

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Control Statements: Part Pearson Education, Inc. All rights reserved.

Expressions, Input, Output and Data Type Conversions

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Functions and Recursion

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Lecture 4 Tao Wang 1

Engineering Problem Solving with C++, Etter/Ingber

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Writing a Good Program. 7. Stream I/O

UNIT- 3 Introduction to C++

COMP322 - Introduction to C++

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C++ Programming: From Problem Analysis to Program Design, Third Edition

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Chapter 3 - Functions

CS242 COMPUTER PROGRAMMING

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

Fundamentals of Programming Session 27

Computing and Statistical Data Analysis Lecture 3

Chapter 3 - Functions

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

PIC10B/1 Winter 2014 Exam I Study Guide

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Objectives. In this chapter, you will:

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Input/Output Streams: Customizing

Introduction to C++ Introduction to C++ 1

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

by Pearson Education, Inc. All Rights Reserved. 2

2 nd Week Lecture Notes

Chapter 8 File Processing

Fundamentals of Programming Session 25

CS201 - Introduction to Programming Glossary By

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

File I/O Christian Schumacher, Info1 D-MAVT 2013

Setting Justification

Chapter 2 Basic Elements of C++

UEE1302 (1102) F10: Introduction to Computers and Programming

Unit-V File operations

Object Oriented Programming Using C++ UNIT-3 I/O Streams

Short Notes of CS201

Cpt S 122 Data Structures. Introduction to C++ Part II

Chapter 2 - Control Structures

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Module C++ I/O System Basics

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Fundamentals of Programming Session 23

10/23/02 21:20:33 IO_Examples

Transcription:

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 usercontrolled 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

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

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;

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

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

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

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 MCQs

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.

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.

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

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

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

Self-Review Exercises CS201 Solved MCQs 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

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.

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

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

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, floatingpoint 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 )

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

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 )

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

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.

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

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.

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

g. a[ 1, 1 ] = 5; CS201 Solved MCQs 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. 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 [Page 390]

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;