CS201 Solved MCQs.

Size: px
Start display at page:

Download "CS201 Solved MCQs."

Transcription

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

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

3 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, , 'Z', 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, and 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 , and display the value Identify the error in each of the following statements and explain how to correct it. a. cout << "Value of x <= y is: " << x <= y;

4 b. c. The following statement should print the integer value of 'c'. d. cout << 'c'; e. cout << ""A string in quotes""; f 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 ) << ; i. j. cout << showbase << oct << 99 << endl << hex << 99; k. l. cout << << endl << showpos << ; m. n. cout << setw( 10 ) << setprecision( 2 ) << scientific << ; 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 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

5 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 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 << ' ' << << ' ' << "Z" << << "String"; ii. jj. cout << cout.precision(); kk.

6 ll. cin >> months >> percentagerate; mm. nn. cout << setprecision( 3 ) << 1.92 << '\t' << << '\t' << ; 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 ) << ; yy 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 b. **123

7 c. 123 d. e. $$$$$10000 f. g h. i j. 0x63 k. l m n. o. 4.45e+002 p. CS201 Solved MCQs

8

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

10 i. Member functions seekp and seekg must seek relative to the beginning of a file 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 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.

11 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 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 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 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 a. Constructors for class string do not exist for integer and

12 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 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 a. ifstream inoldmaster( "oldmast.dat", ios::in ); b. ifstream intransaction( "trans.dat", ios::in );

13 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

14 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

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

16 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

17 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 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; for ( x = 1; x <= 10; x++ ) // loop 10 times 13 cout << cube( x ) << endl; // calculate cube of x and output results return 0; // indicates successful termination 16 } // end main // definition of function cube 19 int cube( int y ) 20 { 21 return y * y * y; 22 } // end function cube

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

19 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 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 ) * * pow( radius, 3 ).

20

21 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; #include <cmath> 12 using namespace std; int main() 15 { 16 cout << fixed << setprecision( 1 ); cout << "sqrt(" << << ") = " << sqrt( ) 19 << "\nsqrt(" << 9.0 << ") = " << sqrt( 9.0 ); 20 cout << "\nexp(" << 1.0 << ") = " << setprecision( 6 ) 21 << exp( 1.0 ) << "\nexp(" << setprecision( 1 ) << << ") = " << setprecision( 6 ) << exp( 2.0 ); 23 cout << "\nlog(" << << ") = " << setprecision( 1 )

22 24 << log( ) 25 << "\nlog(" << setprecision( 6 ) << << ") = " 26 << setprecision( 1 ) << log( ); 27 cout << "\nlog10(" << 1.0 << ") = " << log10( 1.0 ) 28 << "\nlog10(" << 10.0 << ") = " << log10( 10.0 ) 29 << "\nlog10(" << << ") = " << log10( ); 30 cout << "\nfabs(" << 13.5 << ") = " << fabs( 13.5 ) 31 << "\nfabs(" << 0.0 << ") = " << fabs( 0.0 ) 32 << "\nfabs(" << << ") = " << fabs( ); 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 << << ", " << << ") = " 42 << fmod( , 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) = exp(2.0) = log( ) = 1.0 log( ) = 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) = pow(2.0, 7.0) = pow(9.0, 0.5) = 3.0 fmod(13.675, 2.333) = sin(0.0) = 0.0 cos(0.0) = 1.0 tan(0.0) = 0.0

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

24 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) 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; const double PI = ; // define global constant PI // 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 int main() 20 { 21 double radiusvalue; // prompt user for radius 24 cout << "Enter the length of the radius of your sphere: "; 25 cin >> radiusvalue; // input radius // 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

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

26 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 to array element 9. f. Assign the value 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 } };

27 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: 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 ] = [Page 390]

28 fractions[ 7 ] = 0.0 fractions[ 8 ] = 0.0 fractions[ 9 ] = 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] t. [1] u. [2] 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;

Chapter 12 - C++ Stream Input/Output

Chapter 12 - C++ Stream Input/Output Chapter 12 - C++ Stream Input/Output 1 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3

More information

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

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

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

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

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

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

Streams - Object input and output in C++

Streams - Object input and output in C++ Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input

More information

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

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

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

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

Objects and streams and files CS427: Elements of Software Engineering

Objects and streams and files CS427: Elements of Software Engineering Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

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

UEE1303(1070) S 12 Object-Oriented Programming in C++ Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member

More information

C++ Programming Lecture 10 File Processing

C++ Programming Lecture 10 File Processing C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

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

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 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. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

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

Week 3: File I/O and Formatting 3.7 Formatting Output Week 3: File I/O and Formatting 3.7 Formatting Output Formatting: the way a value is printed: Gaddis: 3.7, 3.8, 5.11 CS 1428 Fall 2014 Jill Seaman spacing decimal points, fractional values, number of digits

More information

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

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma. REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout

More information

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

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay Input and Output Data Processing Course, I. Hrivnacova, IPN Orsay Output to the Screen Input from the Keyboard IO Headers Output to a File Input from a File Formatting I. Hrivnacova @ Data Processing Course

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Module 11 The C++ I/O System

Module 11 The C++ I/O System Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...

More information

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

C++ does not, as a part of the language, define how data are sent out and read into the program Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 3 Introduction

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

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.

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. Engineering Problem Solving With C++ 4th Edition Etter TEST BANK Full clear download (no error formating) at: https://testbankreal.com/download/engineering-problem-solving-with-c-4thedition-etter-test-bank/

More information

Fig: iostream class hierarchy

Fig: iostream class hierarchy Unit 6: C++ IO Systems ================== Streams: Θ A stream is a logical device that either produces or consumes information. Θ A stream is linked to a physical device by the I/O system. Θ All streams

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

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

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types. The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++

More information

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

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 4-5 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 3 Assignment, Formatting, and Interactive Input

More information

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

We will exclusively use streams for input and output of data. Intro Programming in C++ C++ Input/Output: Streams The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: 1 istream

More information

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

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

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

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

Control Statements: Part Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

More information

Expressions, Input, Output and Data Type Conversions

Expressions, Input, Output and Data Type Conversions L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with

More information

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss in depth the formatting features

More information

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

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

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

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

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Lecture 4 Tao Wang 1

Lecture 4 Tao Wang 1 Lecture 4 Tao Wang 1 Objectives In this chapter, you will learn about: Assignment operations Formatting numbers for program output Using mathematical library functions Symbolic constants Common programming

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

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

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files. C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++

More information

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

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

More information

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Writing a Good Program. 7. Stream I/O

Writing a Good Program. 7. Stream I/O Writing a Good Program 1 Input and Output I/O implementation is hardware dependent C++ does not, as a part of the language, define how data are sent out and read into the program The input and output (I/O)

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we

More information

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

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7-1 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Conversation / Casting Name Constant - const, #define X When You Mix Apples and Oranges: Type Conversion Operations

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

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

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

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

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14 Chapter 3: Expressions and Interactivity 3.1 The cin Object The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information retrieved from cin with >>

More information

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

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 3.1 The cin Object The cin Object The cin Object in Program 3-1 Standard input object Like cout, requires iostream file Used to read input from keyboard Information

More information

Chapter 3: Expressions and Interactivity

Chapter 3: Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information retrieved from cin with >>

More information

Fundamentals of Programming Session 27

Fundamentals of Programming Session 27 Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Computing and Statistical Data Analysis Lecture 3

Computing and Statistical Data Analysis Lecture 3 Computing and Statistical Data Analysis Lecture 3 Type casting: static_cast, etc. Basic mathematical functions More i/o: formatting tricks Scope, namspaces Functions 1 Type casting Often we need to interpret

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

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

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams Physics 6720 I/O Methods October 30, 2002 We have been using cin and cout to handle input from the keyboard and output to the screen. In these notes we discuss further useful capabilities of these standard

More information

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

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input Input and Output Outline Formatting outputs String data type Interactive inputs File manipulators CS 1410 Comp Sci with C++ Input and Output 1 CS 1410 Comp Sci with C++ Input and Output 2 No I/O is built

More information

PIC10B/1 Winter 2014 Exam I Study Guide

PIC10B/1 Winter 2014 Exam I Study Guide PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

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

The cin Object. cout << Enter the length and the width of the rectangle? ; cin >> length >> width; The cin Object Short for console input. It is used to read data typed at the keyboard. Must include the iostream library. When this instruction is executed, it waits for the user to type, it reads the

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Input/Output Streams: Customizing

Input/Output Streams: Customizing DM560 Introduction to Programming in C++ Input/Output Streams: Customizing Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne Stroustrup]

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

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

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure Computer Systems Computer System Computer Structure C++ Environment Imperative vs. object-oriented programming in C++ Input / Output Primitive data types Software Banking System Compiler Music Player Text

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

Chapter 8 File Processing

Chapter 8 File Processing Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

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

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O

More information

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

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

More information

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

File I/O Christian Schumacher, Info1 D-MAVT 2013 File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential

More information

Setting Justification

Setting Justification Setting Justification Formatted I/O 1 Justification - Justification refers to the alignment of data within a horizontal field. - The default justification in output fields is to the right, with padding

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

Unit-V File operations

Unit-V File operations Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the

More information

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

Object Oriented Programming Using C++ UNIT-3 I/O Streams File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters.

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

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

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

More information

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

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

Module C++ I/O System Basics

Module C++ I/O System Basics 1 Module - 36 C++ I/O System Basics Table of Contents 1. Introduction 2. Stream classes of C++ 3. Predefined Standard Input/Output Streams 4. Functions of class 5. Functions of class

More information

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

C++ As A Better C Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

More information

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

Fundamentals of Programming Session 23

Fundamentals of Programming Session 23 Fundamentals of Programming Session 23 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

10/23/02 21:20:33 IO_Examples

10/23/02 21:20:33 IO_Examples 1 Oct 22 22:07 2000 extractor1.c Page 1 istream &operator>>( istream &in, Point &p ){ char junk; in >> junk >> p.x >> junk >> p.y >> junk; return in; 2 Oct 22 22:07 2000 extractor2.c Page 1 istream &operator>>(

More information