Chapter 6 Quiz Starting Out With C++ 006

Which of the following is the function header?

a. calculateBonus()
b. decimal calculateBonus()
c. return calculatedBonus;

Chapter 6 Quiz Starting Out With C++ 005

What function is automatically called when a program starts in C++?

a. the include function
b. the main function
c. the return function
d. the displayMessage function

Chapter 6 Quiz Starting Out With C++ 004

What is a void function?

a. a function that does not have a body
b. a function that does not return a value
c. a function that doesn't have any parameters
d. a function that doesn't have any arguments

Chapter 6 Quiz Starting Out With C++ 003

Which of the following are parts of the function definition?

a. return type
b. name
c. parameter list
d. argument list
e. body

Chapter 6 Quiz Starting Out With C++ 002

It is a good idea to break up problems into smaller problems that are easily solved?

a. true
b. false

Chapter 6 Quiz Starting Out With C++ 001

A program may be broken up into manageable _____

a. sections
b. blocks
c. subroutines
d. functions

CH5: Programming Challenge: #26

26. Using Files--Savings Account Balance Modification
Modify the Savings Account Balance program described in Programming Challenge 16 so that it writes the final report to a file.

Solution:

CH5: Programming Challenge: #17

17. Sales Bar Chart
Write a program that asks the user to enter today s sales for ve stores. The program should then display a bar graph comparing each store s sales. Create each bar in the bar graph by displaying a row of asterisks. Each asterisk should represent $100 of sales.

Here is an example of the program's output.

Enter today's sales for store 1: 1000 [Enter]
Enter today's sales for store 2: 1200 [Enter]
Enter today's sales for store 3: 1800 [Enter]
Enter today's sales for store 4: 800 [Enter]
Enter today's sales for store 5: 1900 [Enter]
SALES BAR CHART
(Each * = $100)

Store 1: **********
Store 2: ************
Store 3: ******************
Store 4: ********
Store 5: *******************

Solution:

CH5: Programming Challenge: #15

15. Payroll Report
Write a program that displays a weekly payroll report. A loop in the program should ask the user for the employee number, gross pay, state tax, federal tax, and FICA withholdings. The loop will terminate when 0 is entered for the employee number. After the data is entered, the program should display totals for gross pay, state tax, federal tax, FICA withholdings, and net pay. 

Input Validation: Do not accept negative numbers for any of the items entered. Do not accept values for state, federal, or FICA withholdings that are greater than the gross pay. If the sum state tax + federal tax + FICA withholdings for any employee is greater than gross pay, print an error message and ask the user to re-enter the data for that employee.

Solution:

CH5: Programming Challenge: #10

10. Average Rainfall
Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should rst ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.

Input Validation: Do not accept a number less than 1 for the number of years. Do not
accept negative numbers for the monthly rainfall.

Solution:


CH5: Programming Challenge: #2

2. Characters for the ASCII Codes
Write a program that uses a loop to display the characters for the ASCII codes 0 through 127. Display 16 characters on each line.

Solution


Chapter 5 Quiz Starting Out With C++ 043

The _____ statement causes a loop to terminate early. The _____ statement causes a loop to stop its current iteration and begin the next one.

a.. continue, break
b. break, continue

Chapter 5 Quiz Starting Out With C++ 042

Reading and Writing files in C++.  How can you tell if a file was successfully opened in C++?

assume inFile was defined as an ifstream object

a. test ifstream and see if it is true
b. test inFile and check if it is true
c. test open(inFile) == true
d. check if inFile returns an error.

Chapter 5 Quiz Starting Out With C++ 041

Writing and Reading files in C++.  What can be used to read lines of data from a file?

a. the readLine() function
b. a loop
c. cin
d. inFile

Chapter 5 Quiz Starting Out With C++ 040

Reading and Writing files in C++.  Will the following segment of code read the name of a city?

ifstream inFile;
string city;

inFile.open("cities.txt");
cout << "Reading city name from the file.\n";

inFile >> city; // Read the city name from the file

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 039

Writing and Reading files in C++.  The >> operator combined with an ifstream object can be used to read from a file?

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 038

Writing and Reading files in C++.  Given that outFile has been defined with ofstream, which statement will write the data to a file?

a. cout(outFile) << " Hello Student";
b. cout << outFile << "Hello Student";
c. outFile << "Hello Student";
d. outFile -> "Hello Student";

Chapter 5 Quiz Starting Out With C++ 037

Writing and Reading a file in C++.  How do you close a file in C++?

a. ifstream inFile.close();
b. inFile.Close();
c. inFile.close();
d. close(inFile);

Chapter 5 Quiz Starting Out With C++ 036

Reading and Writing files in C++.  What does the following statement do?

ifstream inFile("NewHires.txt");

a. defines a input file stream  named inFile and opens the file NewHires.txt.
b. defines the input stream but does not open it.
c. checks to see if the file NewHires.txt exists
d. none of the above.  You can't do all that in one statement

Chapter 5 Quiz Starting Out With C++ 035

_____ backslashes are required to represent one blackslash when setting the path of a file in a string.

a. two
b. three
c. one

Chapter 5 Quiz Starting Out With C++ 034

Reading and Writing files in C++.  Is this how you set up a file for output in C++?

ofstream outFile;
outFile.open("Sales.txt");

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 033

Writing and Reading files in C++.  The following is the correct way to set up a file for reading?

ifstream inFile;
inFile.open("Employees.txt");

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 032

Reading and Writing files in C++.  _____ is used for output, _____ is used for input and _____ is used for reading or writing.

a.  fstream, ofstream, ifstream
b. ifstream, ofstream, fstream
c. ifstream, fstream, ofstream
d. fstream, fstream, fstream

Chapter 5 Quiz Starting Out With C++ 031

Reading and Writing files in C++.  _____ contains all the declarations necessary for file operations.

a. fileIOstream
b. file.h
c. fstream
d. fileReadWrite

Chapter 5 Quiz Starting Out With C++ 030

Writing and Reading files in C++.  What must be created in order to be able to work with files/

a. filesys link
b. file stream object
c. binary stream
d. random access link

Chapter 5 Quiz Starting Out With C++ 029

Writing and Reading files in C++.  Random access files or direct access files are considered the same thing?

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 028

Reading and Writing files in C++.  Sequential access files can be accessed at any location in the file.  This may include forward and backwards?

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 027

Reading a writing files in C++.  A _____ file can be easy read by human eyes, whereas a _____ file is more difficult.

a. binary, ASCII
b. ASCII, binary
c. text, ASCII
d. ASCII, text

Chapter 5 Quiz Starting Out With C++ 026

Using data files in C++.  What are the steps required for using a file in a program in C++?

a.  Process the file, Open the file, Close the file
b. Open the file, Process the file, Close the file
c. Close the file, Process the file, Open the file

Chapter 5 Quiz Starting Out With C++ 025

A loop that is inside another loop is called a _____?

a. internal loop
b. indented loop
c. blocked loop
d. nested loop

Chapter 5 Quiz Starting Out With C++ 024

The file temp.txt has the following values.  What is probably the sentinel value?

98, 101, 95, 93, 85, 73, 73, 75, 0

a. 98
b. 0
c. 85
d. \n

Chapter 5 Quiz Starting Out With C++ 023

What is a sentinel in C++? (mark the best answer)

a. a sentinel is a special value that marks the end of a list of values.
b. a routine that makes performs validation on the values
c. a sentinel is always -1 and terminates a list of values
d. a sentinel is a special value that is defined by the user.

Chapter 5 Quiz Starting Out With C++ 022

A _____ is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the running total is called an _____.

a. accumulator, running total
b. running total, accumulator


Chapter 5 Quiz Starting Out With C++ 021

Can you omit or leave out the initialization expression from a for-loop?

int i= 1;
int maxVal=10;

for ( ; i<= maxVal; i++)
   cout << i << "\t\t" << (i * i) << "\n";

a. yes, if you have already initialized the test variable
b. yes, the for loop will automatically create the variable i and set it to 0
c. no, the compiler will generate an error
d. no, the program will run and then give a syntax error once you hit the loop

Chapter 5 Quiz Starting Out With C++ 020

Which of the following is the best answer.  In a for loop, the counter can only be incremented or decremented by 1.

a. the counter can only be counter++ or counter--
b. no, you can do increment/decrement other than by 1.  counter+=2
c. yes



Chapter 5 Quiz Starting Out With C++ 019

Which of the following loop mechanisms are pretest loops in C++?

a. for loops
b. while loops
c. do while loops
d. a and c
e. a and b

Chapter 5 Quiz Starting Out With C++ 018

Can you use for-loop, do-while and while looping to perform identically?

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 017

Can you declare and initialize in a variable that will be used in the test expression?

for (int i=0; i<100; i++)
{
   //display the square of the numbers from 0 to 99
   cout << i*i << "\n";
}

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 016

Is the following a correct format for the for-loop?

for (initialization; test expression; update)
{
   statement;
   statement;
   .
   .
}

a. true
b. false


Chapter 5 Quiz Starting Out With C++ 015

What are the steps involved in a for-loop in C++?

a. initialize, perform update expression, test expression, and finally execute body
b. execute body, initialize, perform update expression, test expression
c. initialize, execute body,  test expression, perform update expression
d. initialize, test expression, execute body, perform update expression

(remember the slide from 9/30/13)

Chapter 5 Quiz Starting Out With C++ 014

If you can determine ahead of time how many times a loop will be performed then a for-loop is commonly used.

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 013

How do you prevent infinite loops?

a. make sure you test at the beginning of the loop
b. make sure something inside the loop changes the test expression to false
c. make sure you have plenty of RAM
d. it is impossible to prevent infinite loops.
e. make sure something inside the loop changes the test expression to true

Chapter 5 Quiz Starting Out With C++ 012

Which of the following is an example of an infinite loop

a.
x=1;
while (x>=1)
   cout << "I'm in a loop";
b.
while infinite ()
   cout << "I'm in a loop";
c.
while ()
{
   cout << "I'm in a loop";
}

d.
x=10;
while (x >0)
{
   x--;
   cout << "I'm in a loop";
}


Chapter 5 Quiz Starting Out With C++ 011

The _____ is pretest loop and the _____ is a posttest loop

a. do-while loop, while loop
b. while loop, do-while loop
c. repeat loop, while loop
d. while loop, repeat loop

Chapter 5 Quiz Starting Out With C++ 010

The while loop is usually used when you know the exact number of times a loop will repeat

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 009

What is the format of the while loop in C++?

a.

while ( x >5)
do {
   y++;
}

b.

perform 
{
   y++;
} while (x >5)

c.

while (x >5)
{
   y++;
}

Chapter 5 Quiz Starting Out With C++ 008

A _____ is a part of a program that repeats

a. function
b. loop
c. repeat
d. branch statement

Chapter 5 Quiz Starting Out With C++ 007

Can you use increment or decrement in relationship expressions?

if (x++ > 10)
  cout << "Thanks for playing!";

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 006

Given that x is 5 and y is 4 what will this code segment produce

z = ++(x + y);

a. 11
b. 10
c. a syntax error
d. a compilation error

Chapter 5 Quiz Starting Out With C++ 005

Given the following code.  Will anything be displayed?

z = 130;
if (x++ > 130)
cout << "z is greater than 130.\n";

a. true
b. false

Chapter 5 Quiz Starting Out With C++ 004

What is the difference between prefix and postfix when dealing with statements that do more than incrementing or decrementing?

a. nothing.
b. prefix will increment/decrement BEFORE the variable is used.
c. postfix will increment/decrement BEFORE the variable is used.
d. both will preform the increment/decrement AFTER the variable is used

Chapter 5 Quiz Starting Out With C++ 003

Given that x is 5 in the snippet below.  What will be displayed by the cout statement?

x = 5;
cout << x++;

a. 6
b. 7
c. 5
d. 4


Chapter 5 Quiz Starting Out With C++ 002

The first example is _____ mode and the second is _____ mode?

i++, ++j

a. prefix, postfix
b. postfix, prefix
c. post inc, pre inc
d. pre inc, post inc

Chapter 5 Quiz Starting Out With C++ 001

How do you use the increment and decrement operators in C++?

a. x++,  x--
b. x = x + 1, x = x -1
c. inc x, dec x
d. both a and b are acceptable
e.  answer a, c.  One is C language and the other is C++

Chapter 4 Quiz Starting Out With C++ 047

Can you have two variables with the same name in C++?

a. only if they are in the same scope
b. only if they are in different blocks
c. if one of the variables is in a function
d. heck, I wasn't listening when we went over this. idk

Chapter 4 Quiz Starting Out With C++ 046

The switch statement lets the value of a variable or expression determine where the program will branch in an if/else statement

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 045

Since it takes three operands, the conditional operator is considered a
ternary operator.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 044

Which of the following is an example of a conditional operator?

a.
x > y ? z=1 : z=0;

b.
if (x>y)
   z=1
else
  z=0;

c.
if x>y then z=1 else z=0

d.
? (x>y) : z=1 : z=0;

Chapter 4 Quiz Starting Out With C++ 043

The conditional operator works like an if/else statement

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 042

What do the ASCII values 65 through 90 represent?

a. the numbers from 65 through 90 as integers.
b. the characters 'a' through 'z'
c. the characters 'A' through 'Z'
d. the characters '0' through '9'
e. none.  ASCII is obsolete and no longer used.

Chapter 4 Quiz Starting Out With C++ 041

The highest or of precedence in C++ is

a. ||
b. !
c. &&
d. they are all the same.  Left to right

Chapter 4 Quiz Starting Out With C++ 040

Precedence is not important in C++

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 039

What does || mean in C++?

a. OR
b. NOT
c. EITHER

Chapter 4 Quiz Starting Out With C++ 038

What is the value of the following expression?

true && false

a. true
b. false
c. can't tell
d. the expression makes no sense in C++

Chapter 4 Quiz Starting Out With C++ 037

In C++, the ______ operator reverses the "truth" of an expression.  It makes a true expression false and a false expression true.

a. &&
b. !
c. ||
d. reverse()
e. none of the above

Chapter 4 Quiz Starting Out With C++ 036

_____ operators connect two or more relational expressions into one or reverse the logic of an expression?

a. syntax
b. binary
c. logical
d. combinatory
e. answer b and c

Chapter 4 Quiz Starting Out With C++ 035

What is typically used as a flag in C++

a. a float
b. an integer
c. a bool
d. a register
e. b and c
ab. answer c is typical but answer b is also used by some
ae. none of the above.  C++ does not have access to the AX or BX flags of the CPU

Chapter 4 Quiz Starting Out With C++ 034

The potential round-off errors are common if the user is not careful when the user uses the equality operator to compare floating point values.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 033

What is the operator that can be used for the logical AND ?

a. &&
b. ++
c. ||
d. @
e. AND

Chapter 4 Quiz Starting Out With C++ 032

What is the value for a relational operation when it is not true?

a. one
b. zero
c. zero, one, or minus one
d. less than zero

Chapter 4 Quiz Starting Out With C++ 031

The following C++ statement will let the variable decide where the program will go to.

a. select
b. associative
c. scope
d. switch
e. none of the above

Chapter 4 Quiz Starting Out With C++ 030

When you use input values, the user should check for the following:

a. Appropriate range
b. Reasonableness
c. Division by zero, if division is taking place
d. All of these
e. None of the above

Chapter 4 Quiz Starting Out With C++ 029

An if statement considers true any value that is NOT 0 (ZERO)

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 028

When a user writes an if statement, the user should indent the statements that get executed conditionally based on programming style.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 027

The switch statement does not require the default section.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 026

If a conditionally-executed code of another if statement contains an if statement, this is called:

a. complexity
b. overloading
c. nesting
d. validation

Chapter 4 Quiz Starting Out With C++ 025

You can ____________ numbers with relational operators.

a. average 
b. add
c. multiply
d. compare

Chapter 4 Quiz Starting Out With C++ 024

What operators can you choose to subtract 1 from their operands.

a. unary
b. minus
c. --
d. relational

Chapter 4 Quiz Starting Out With C++ 023

You may nest for loops like the while and do-while loops.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 022

An initialization expression may be omitted from the for loop if initialization is required.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 021

The condition that is tested by a while loop must be enclosed in parentheses and terminated with a semicolon.

a. True
b. False

Chapter 4 Quiz Starting Out With C++ 020

Using the following word, we mean that we add 1 to the value.

a. modulus
b. decrement
c. increment
d. parse

Chapter 4 Quiz Starting Out With C++ 019

What is the name of a loop that is inside another one?

a. an infinite loop
b. a pre-test loop
c. a nested loop
d. a post-test loop

Chapter 4 Quiz Starting Out With C++ 018

Which of the following is an important part of a while loop:

a. a statement or block that is repeated as long as the expression is true
b. a statement or block that is repeated only if the expression is false
c. one line of code that is repeated once, if the expression is true
d. a statement or block that is repeated once, if the expression is true

Chapter 4 Quiz Starting Out With C++ 017

You can include multiple statements in the body of a while loop, if you enclose them in braces.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 016

The test condition of a for loop cannot include multiple relational expressions.

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 015

What will be displayed after the following is executed given that grade is 90

if ( grade > 90 )
 cout << "Congrats on getting an 'A'";
else
 cout << "You almost got an 'A' better luck next time.";
 cout << "Try harder next time.";


a. Congrats on getting an 'A'
b. You almost got an 'A' better luck next time.
c. You almost got an 'A' better luck next time.
   Try harder next time.
d. You almost got an 'A' better luck next time.Try harder next time.
e. None of the above

Chapter 4 Quiz Starting Out With C++ 014

What is the value of x after the following snippet of code is executed given that x is 3

if (x == 3)
    x++;
    x++;


a. 4
b. 1
c. 5
d. 7

Chapter 4 Quiz Starting Out With C++ 013

Let's analyze the following statement assuming that y is 6.

if ( y = 7 )
   cout << " y is 7.  How lucky of you. ";
else
  cout << "y is not 7.  Sorry about that.";

What will be the result of this section of code.

a.  cout << "y is not 7.  Sorry about that.";
b. cout << " y is 7.  How lucky of you. "; //will always execute regardless of the value of y
c. y=7 is an assignment and not a comparison will not compile
d. I was texting in class and have no absolutely no idea.
e. This will compile but completely skip both statements.

Chapter 4 Quiz Starting Out With C++ 012

Putting a semicolon after the if (expression) is a common mistake and will lead to a compiler error

if (x>y);
  temp++;

a. false
b. today's compilers are smart enough and will remove the semi-colon
c. you'll get a warning message but the compiler knows what you mean
d. true

Chapter 4 Quiz Starting Out With C++ 011

In C++, you can only have one statement following a relational test?

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 010

if (expression)
  statement;
else
  statement;

Does the above work in C++?

a. true
b. false

Chapter 4 Quiz Starting Out With C++ 009

How do you write an "if" statement in C++?  Which sample below is the best

a.
  if (x >y) then
{
   tmp++;
}

b.
if ( x >y )
 tmp++;

c.
 if x>y
  tmp++
else
 tmp--;

d.
None of the above.  They won't compile

Chapter 4 Quiz Starting Out With C++ 008

What is the value of the relation expression below, given that x is 5 and y is 1.  z is a bool.

z = x < y;

a. true
b. false
c. 1
d. 0
e. None of the above, you can't assign result of expression, only test it

Chapter 4 Quiz Starting Out With C++ 007

(bonus question) How does C++ handle true or false with regards to storing these values. Mark all that apply, if any

a. only a 1 is equal to true.
b. only 0 is considered true.
c.  a 0 is considered false.
d. anything other than 0 is considered true.
e. None of the above, they are stored as T or F.

Remember the lecture from Monday on making decisions and you'll do fine.

Chapter 4 Quiz Starting Out With C++ 006

In the following, what is the value of the expression given that the value of x is 5?

x == 5

a. x
b. 5
c. false
d. true

Chapter 4 Quiz Starting Out With C++ 005

What does the ! (exclamation symbol) mean in c++?

a. It tells the compiler to check this condition first
b. It means not or the opposite of what the comparison is.
c. It is a shortcut so you don't have to enter 'true' or a relational comparison operator
d. None of the above

Chapter 4 Quiz Starting Out With C++ 004

What is the difference between = and == in C++?

a. They are the same but the == makes it more visible to the programmer
b. == is used to assign a value to a variable and = is used to compare.
c. = is used to assign a value to a variable.
d. == is used for comparison and = is used to assign

Chapter 4 Quiz Starting Out With C++ 003

How do you write "greater than or equal to" test in c++?

a. gte
b. > or =
c. >=
d. > && =

Chapter 4 Quiz Starting Out With C++ 002

What does x <= y mean?

a. x is less than y
b. x is less than or equal to y
c. assign the value of y to x if x less than
d. none of the above

Chapter 4 Quiz Starting Out With C++ 001

Which of the following is not a relational operator?

a. ==
b. >
c. <
d. =

Chapter 3 Quiz Starting Out With C++ 040

What is the purpose of flowcharting?

a. plan out the program before coding
b. Mr. Daniels likes pretty symbols
c. visual display of the program
d. all of the above

Chapter 3 Quiz Starting Out With C++ 039

How to you get a random number in C++?

a. x=rnd();
b. x=random();
c. x=rand();
d. x=randomNum();

Chapter 3 Quiz Starting Out With C++ 038

 C++ has a runtime library for performing math?

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 037

 The cin.ignore function tells the cin object to skip one or more characters in the keyboard buffer.

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 036

cin.get is used for reading in characters

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 035

What does getline do?

a. reads an entire line including whitespaces
b. reads an entire line except whitespaces
c. a whole word
d. none of the above

Chapter 3 Quiz Starting Out With C++ 034

 What are whitespace characters?

a. spaces
b. spaces and tabs only
c. spaces, tabs, or line breaks
d. none of the above

Chapter 3 Quiz Starting Out With C++ 033

Which of the following statements will display the following result if x is 123.4?

123.400

a. cout << setprecision(6) << showpoint << x << endl;
b. cout << setw(6) << x << endl;
c. cout << showpoint << x << endl;
d. cout << showpoint(3) << x << endl;

Chapter 3 Quiz Starting Out With C++ 032

What do you use to print digits in fixed-point notation or decimal?

a. setprecision
b. setw
c. fixedpoint
d. fixed

Chapter 3 Quiz Starting Out With C++ 031

 You can control the number of significant digits with which floating-point values are displayed by using the

a. setw
b. significant
c. setprecision
d. cast

Chapter 3 Quiz Starting Out With C++ 030

setw

a. sets the width of the screen
b. establishes print fields of a specified width
c. sets the precision of the variable
d. None of the above

Chapter 3 Quiz Starting Out With C++ 029

 _____ provides a way to output data and _____ allows for input of data

a. cin, cout
b. input, output
c. cout, cin
d. output, input


Chapter 3 Quiz Starting Out With C++ 028

Will the following produce the same result?

x *= 5       x = x * 5

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 027

 What does the value of x in the code fragment below?

c = 5;
x = 5 * (c++);

a. 6
b. 25
c. 30
d. 0 (since c++ has not been defined

Chapter 3 Quiz Starting Out With C++ 026

Is the following a valid assignment?

x = y = z = 10;

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 025

Can multiple assignments be used in C++

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 024

What is type casting in C++

a. manually promoting or demoting a value
b. forcing an integer to hold a double or float
c. making it possible to add two different type variables to be added
d. None of the above

Chapter 3 Quiz Starting Out With C++ 023

What is an Overflow

a. When you try to use a value larger the the data type of the variable
b. When the computer runs out of memory
c. When a variable is uninitialized
d. None of the above

Chapter 3 Quiz Starting Out With C++ 022

In C++, if you divide the integers 7 by 2 the answer will be

a. 3.5
b. 3
c. 2
d. undefined since the answer is a float

Chapter 3 Quiz Starting Out With C++ 021

 When the final value of an expression is assigned to a variable, it will be converted
to the data type of that variable.

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 020

When an operator works with two values of different data types, the lower-ranking
value is promoted to the type of the higher-ranking value.

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 019

chars, shorts, and unsigned shorts are automatically promoted to type int.

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 018

What happens in C++ when operator's operands are of different types?

a. Nothing
b. C++ will convert to the same data type
c. C++ will convert to the largest data type
d. C++ will convert to the lowest data type

Chapter 3 Quiz Starting Out With C++ 017

 To calculate the average of two numbers in C++

a. x + y/2
b. (x + y)/2
c. x/2 + y
d. All of the above

Chapter 3 Quiz Starting Out With C++ 016

 How do you do exponents in C++ for 2.0 raised to 4.0

a. 2.0^4.0
b. pow(2.0, 4.0)
c. 2.0*4.0
d. None of the above

Chapter 3 Quiz Starting Out With C++ 015

How do you write the sum of X plus Y divided by Z in C++

a. x + y/z
b. (x +y)/z
c. X + Y/Z
d. (X + Y)/Z

Chapter 3 Quiz Starting Out With C++ 014

In the following expression what is the answer

6 * (2 + 4) - 5

a. 11
b. 31
c. 6
d. None of the above

Chapter 3 Quiz Starting Out With C++ 013

 What has the lowest precedence?

a. * (asterick)
b. / (division)
c. + (plus)
d. - (unary negation)

Chapter 3 Quiz Starting Out With C++ 012

What is operator precedence?

a. What numbers will be processed first.
b. What expressions are stored before others
c. Some types are stored higher in memory
d. Some operators are evaluated before others

Chapter 3 Quiz Starting Out With C++ 011

11) What is an expression in C++

a. An expression is how you declare a variable
b. An expression describes whether a variable has a value or not
c. An expression is a compiler command
d. An expression is a programming statement that has a value

Chapter 3 Quiz Starting Out With C++ 010

10) Can the cin object read in values of different types?

a. Yes, they must be all the same type
b. Yes, they can be different but separated by commas
c. Yes, only if the other type is a string
d. No, only one type.

Chapter 3 Quiz Starting Out With C++ 009

9) What key is pressed after the last input value using cin

a. TAB
b. ENTER
c. SPACE
d. DOWNARROW

Chapter 3 Quiz Starting Out With C++ 009

9) What key is pressed after the last input value when you are using cin?

a. TAB
b. ENTER
c. SPACE
d. DOWNARROW

Chapter 3 Quiz Starting Out With C++ 008

8) What file must you include to get cin to work?

a. cin.h
b. input
c. iostream
d. keyboard

Chapter 3 Quiz Starting Out With C++ 007

7) Can cin read in more than one value?

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 006

6) >> is used for ____ and << is used for _____

a. input, output
b. output, input
c. cin, cout
d. cout, cin

Chapter 3 Quiz Starting Out With C++ 005

5) It is usually a good practice to display a prompt before gathering input

a. True
b. False

Chapter 3 Quiz Starting Out With C++ 004

4) What is the >> in C++

a. console standard input redirector
b. input funneling operator
c. stream extraction operator
d. all of the above

Chapter 3 Quiz Starting Out With C++ 003

3) How do you read in a value from the keyboard and assign it to variable number?

a. cin >> number;
b. cin << number;
c. cin > number;
d. cin < number;

Chapter 3 Quiz Starting Out With C++ 002

2) What is the standard input object in C++

a. cin
b. cout
c. readLine()
d. dataRead()

Chapter 3 Quiz Starting Out With C++ 001

1) How is input read in C++?

a. The cin object reads in input from the keyboard
b. The System.Console.Input function
c. Readline()
d. cin.dataRead()

Chapter 2 Quiz Starting Out With C++ 020

20) An escape sequence starts with a double quote?

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 019

19) cout can only output one item per line?

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 018

18) The # symbol marks the beginning of what?

a. a program
b. preprocessor directive
c. comment
d. None of the Above

Chapter 2 Quiz Starting Out With C++ 017

17) Forgetting either an opening { or closing } brace is a common reason a C++ program won't compile

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 016

16) What character terminates C++ statements?

a. space
b. semicolon
c. endl
d. none

Chapter 2 Quiz Starting Out With C++ 015

15) What function is required by all C++ programs?

a. init
b. processor
c. syntax analyzer
d. main

Chapter 2 Quiz Starting Out With C++ 014

14) A function is a group of one or more statements that collectively has a name?

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 013

13) C++ uses namespaces to:

a. organize the names of program entities
b. to make entities easier to find
c. speed up compiling
d. make programs easier to read

Chapter 2 Quiz Starting Out With C++ 012

12) The preprocessor directive, #include <iostream>, is required for all C++ programs

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 011

11) What marks the beginning of a comment in a C++ program?

a. // (The double slash)
b. ' (The single quote'
c. REM
d. COMMENT:

Chapter 2 Quiz Starting Out With C++ 010

10) What is the header file that has to be included to allow access to the file?

a. file
b. fileaccess
c. fstream
d. cfile

Chapter 2 Quiz Starting Out With C++ 009

9) You can not store a string in an array of characters.

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 008

8) There are more differences between the get function and the >> operator than that get reads the first character typed, even if it is a space, tab, or the [Enter] key.

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 007

7) You need to enter the length, width, and height while executing a program. Which cin statement should be used from the following?

a. cin << length, width, height;
b. cin.get(length, width, height);
c. cin >> length >> width >> height;
d. cin >> length, width, height;

Chapter 2 Quiz Starting Out With C++ 006

6) One of the following will make a program to remain inactive until information will be entered at the keyboard and the user presses the Enter key.

a. Output stream
b. cin object
c. cout object
d. Preprocessor

Chapter 2 Quiz Starting Out With C++ 005

5) When a variable is used to assign a value that will be the result of an expression, it will be changed to:

a. The smallest C++ data type
b. The largest C++ data type
c. The data type of the variable
d. The data type of the expression

Chapter 2 Quiz Starting Out With C++ 004

4) If you wanted to have a number being displayed in scientific notation, you may use the Fixed manipulator.

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 003

3) The setprecision manipulator will be the exact number of digits to show before the decimal point in case of the fixed manipulator.

a. True
b. False

Chapter 2 Quiz Starting Out With C++ 002

2) When an object, that is used to enter data by the user, like the cin object, the following ___________must be with it.

a. compiler
b. iostream header file
c. linker
d. >> and << operators

Chapter 2 Quiz Starting Out With C++ 001

1) You can display in C++ the number 45.211 in a field of 9 spaces with 2 decimal places.

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 027

Which statement is true

a. C++ is object-oriented
b. C is object-oriented
c. C can run all C++ programs
d. All of the above

Chapter 1 Quiz Starting Out With C++ 026

C++ can be used to do the following type of programming

a. Procedural
b. object-oriented
c. Both a and b
d. None of the above

Chapter 1 Quiz Starting Out With C++ 025

It is very common for commercial software to be developed by one programmer

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 024

A software engineer does the following

a. Designs
b. Writes
c. Tests
d. All of the above

Chapter 1 Quiz Starting Out With C++ 023

C++ is not popular because it is portable


a. True
b. False

Chapter 1 Quiz Starting Out With C++ 022

C, C++, C# and Java are considered

a. Machine languages
b. High level languages
c. Binary languages
d. 4th Generation languages

Chapter 1 Quiz Starting Out With C++ 021

A compiler falls into what type of systems software

a. Operating Systems
b. Utility Programs
c. Software Development Tools
d. All of the above

Chapter 1 Quiz Starting Out With C++ 020

Microsoft Word would considered an operating system program

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 019

Which of the following use flash memory

a. DVD
b. CD
c. USB Drive
d. Floppy Disk Drive

Chapter 1 Quiz Starting Out With C++ 018

Most computers have a disk drive installed inside their case

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 017

The difference between RAM and ROM

a. Nothing
b. Contents of RAM remain after you turn off the computer
c. Contents of ROM remain after you turn off the computer
d. ROM is back up storage when RAM is filled

Chapter 1 Quiz Starting Out With C++ 016

What is the next step after fetch and decode?

a. End
b. Enter
c. Execute
d. None of the above

Chapter 1 Quiz Starting Out With C++ 015

The CPU consists of three parts: control unit, arithmetic and logic unit, and cooling unit

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 014

What does CPU stand for:

a. Centrally Positioned Unit
b. Central Processing Unit
c. Core Processing Utility
d. Core Positioned Utility

Chapter 1 Quiz Starting Out With C++ 013

All professional programmers create software that runs correctly the first time.

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 012

A person that creates software is called a:

a. Software developer
b. Programmer
c. Software engineer
d. All of the above
e. None of the above

Chapter 1 Quiz Starting Out With C++ 011

In C++, key words are written in all lowercase letters.

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 010

The preprocessor executes after the compiler.

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 009

This step will uncover any syntax errors in your program.

a. Editing
b. Compiling
c. Linking
d. Executing

Chapter 1 Quiz Starting Out With C++ 008

Programs are commonly called:

a. Execution statements
b. Software
c. By the operating System
d. Automatically when clicked

Chapter 1 Quiz Starting Out With C++ 007

A CPU really only understands instructions that are written in machine language.

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 006

Three primary activities of a program are:

a. Variables, Operators, and Key Words
b. Lines, Statements, and Punctuation
c. Input, Processing, and Output
d. Integer, Floating-point and Character

Chapter 1 Quiz Starting Out With C++ 005

Programmer-defined names of memory locations that may hold data are:

a. Operators
b. Variables
c. Syntax
d. Operands

Chapter 1 Quiz Starting Out With C++ 004

An Integrated Development Environment typically consists of:

a. A text editor
b. A compiler
c. A debugger
d. All of the above

Chapter 1 Quiz Starting Out With C++ 003

The preprocessor executes after the compiler.

a. True
b. False

Chapter 1 Quiz Starting Out With C++ 002


The programming process consists of several steps, which include:

a. Input, Processing, and Output
b. Key Words, Operators, and Punctuation
c. Design, Creation, Testing, and Debugging
d. Syntax, Logic, and Error Handling

Chapter 1 Quiz Starting Out With C++ 001

Which of the following best describes an operator?

a. An operator is a rule that must be followed when constructing a program.
b. An operator allows you to perform operations on one or more pieces of data.
c. An operator marks the beginning or ending of a statement, or is used to separate items in a list.
d. An operator is a word that has a special meaning.

13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10896

Question

Write the interface (.h file) of a class  GasTank containing:
A data member named  amount of type double.
A data member named  capacity of type double.
A constructor that accepts a parameter of type double.
A function named  addGas that accepts a parameter of type double and returns no value.
A function named  useGas that accepts a parameter of type double and returns no value.
A function named  isEmpty that accepts no parameters and returns a boolean value.
A function named  isFull that accepts no parameters and returns a boolean value.
A function named  getGasLevel that accepts no parameters and returns a double.
A function named  fillUp that accepts no parameters and returns a double.

Solution
class GasTank
{
    private:
        double amount;
        double capacity;

    public:
        GasTank(double);
        void addGas(double);
        void useGas(double);
        bool isEmpty();
        bool isFull();
        double getGasLevel();
        double fillUp();
};

13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10889

Question

Write the implementation (.cpp file) of the  Averager class of the previous exercise. The full specification of the class is:
An data member named  sum of type integer.
An data member named  count of type integer.
A constructor with no parameters. The constructor initializes the data members  sum and the data member  count to 0.
A function named  getSum that accepts no parameters and returns an integer.  getSum returns the value of  sum .
A function named  add that accepts an integer parameter and returns no value.  add increases the value of  sum by the value of the parameter, and increments the value of  count by one.
A function named  getCount that accepts no parameters and returns an integer.  getCount returns the value of the  count data member, that is, the number of values added to  sum .
A function named  getAverage that accepts no parameters and returns a double.  getAverage returns the average of the values added to  sum . The value returned should be a value of type double (and therefore you must cast the data members to double prior to performing the division).

Solution
Averager::Averager()
{
    sum=0;
    count=0;
}

int Averager::getSum()
{
    return sum;
}

void Averager::add(int theNum)
{
    sum+=theNum;
    count++;
}

int Averager::getCount()
{
    return count;
}

double Averager::getAverage()
{
    return (double) sum / (double) count;
}

13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10885

Question

Write the implementation (.cpp file) of the  Accumulator class of the previous exercise. The full specification of the class is:
An data member named  sum of type integer.
A constructor that accepts no parameters. The constructor initializes the data member  sum to 0.
A function named  getSum that accepts no parameters and returns an integer.  getSum returns the value of  sum .
A function named  add that accepts an integer parameter and returns no value.  add increases the value of  sum by the value of the parameter.

Solution
Accumulator::Accumulator()
{
    sum=0;
}

int Accumulator::getSum()
{
    return sum;
}

void Accumulator::add(int theNum)
{
    sum+=theNum;
}

13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10877

Question

Write the implementation (.cpp file) of the  Counter class of the previous exercise. The full specification of the class is:
A data member  counter of type  int .
An data member named  limit of type  int .
A static  int data member named  nCounters which is initialized to  0 .
A constructor that takes two  int arguments and assigns the first one to  counter and the second one to  limit . It also adds one to the static variable  nCounters
A function called  increment that accepts no parameters and returns no value. If the data member  counter is less than  limit ,  increment just adds one to the instance variable  counter .
A function called  decrement that accepts no parameters and returns no value. If  counter is greater than zero,  decrement subtracts one from the  counter .
A function called  getValue that accepts no parameters. It returns the value of the instance variable  counter .
A static function named  getNCounters that accepts no parameters and return an  int .  getNCounters returns the value of the static variable  nCounters .

Solution
int Counter::nCounters = 0;

Counter::Counter(int theCounter, int theLimit)
{
        nCounters++;
        counter = theCounter;
        limit=theLimit;
}

void Counter::increment()
{
    if (counter<limit)
        counter++;
}

void Counter::decrement()
{
    if (counter>0)
        counter--;
}

int Counter::getValue()
{
    return counter;
}


int Counter::getNCounters()
{
    return nCounters;
}

13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10854

Question

Write the interface (.h file) of a class  Counter containing:
An instance variable  counter of type  int , initialized to 0.
A function called  increment that adds one to the instance variable  counter . It does not accept parameters or return a value.
A function called  getValue that doesn't accept any parameters. It returns the value of the instance variable  counter .
A default constructor.

Solution
class Counter {

private:
int counter;

public:
void increment();
int getValue();
Counter();
};

13.5 Focus on Software Engineering: Separating Class Specification from Implementation: 10853

Question

Write the implementation (.cpp file) of the  ContestResult class from the previous exercise. Again, the class contains:
An instance variable  winner of type  string , initialized to the empty string.
An instance variable  secondPlace of type  string , initialized to the empty string.
An instance variable  thirdPlace of type  String , initialized to the empty string.
A function called  setWinner that has one parameter, whose value it assigns to the instance variable  winner .
A function called  setSecondPlace that has one parameter, whose value it assigns to the instance variable  secondPlace .
A function called  setThirdPlace that has one parameter, whose value it assigns to the instance variable  thirdPlace .
A function called  getWinner that has no parameters and that returns the value of the instance variable  winner .
A function called  getSecondPlace that has no parameters and that returns the value of the instance variable  secondPlace .
A function called  getThirdPlace that has no parameters and that returns the value of the instance variable  thirdPlace .

Solution
void ContestResult::setWinner (string theWinner)
{
    winner = theWinner;
}

void ContestResult::setSecondPlace (string theSecondPlace)
{
    secondPlace = theSecondPlace;
}

void ContestResult::setThirdPlace (string theThirdPlace)
{
    thirdPlace = theThirdPlace;
}

string ContestResult::getWinner ()
{
    return winner;
}

string ContestResult::getSecondPlace()
{
    return secondPlace;
}

string ContestResult::getThirdPlace()
{
    return thirdPlace;
}

13.3: Defining an Instance of a Class in C++: 11204

Question

Creating objects of the Currency class require a name (string), a currency symbol (string) and the number of decimal places (integer) usually associated with the currency (in that order). Creating objects of the Money class require a Currency object, and the actual amount (integer) (in that order). Define an object of type Currency named canadianDollars and corresponding to the name "Canadian Dollar", the symbol "C$", and 2 decimal places. Define an object of type Money named valueInCanadians corresponding to 230 units of canadianDollars.

Solution
Currency canadianDollars ("Canadian Dollar", "C$", 2);
Money valueInCanadians (canadianDollars,230);

13.3: Defining an Instance of a Class in C++: 11200

Question

Objects of the Window class require a width (integer) and a height (integer) be specified (in that order) upon definition. Declare two integers corresponding to a width and a length and read values into them from standard input (in that order). Use these value to define an object of type Window named newWindow.

Solution
int width, length;
cin >> width >> length;
Window newWindow (width, length);

13.3: Defining an Instance of a Class in C++: 11198

Question

Objects of the Window class require a width (integer) and a height (integer) be specified (in that order) upon definition. Define an object named window, of type Window, corresponding to a 80 x 20 window.

Solution
Window window (80,20);

13.3: Defining an Instance of a Class in C++: 11196

Question

Objects of the BankAccount class require a name (string) and a social security number (string) be specified (in that order)upon creation. Define an object named  account , of type  BankAccount , using the values "John Smith" and "123-45-6789" as the name and social security number respectively.

Solution
BankAccount account ("John Smith", "123-45-6789");

CH12: Programming Challenge #15

Question
I only have a partial...anyone have more info send via comment.

SC-CUSTOM EXERCISE

12.9: Random-Access Files with C++

I don't have the questions, if you have them send via comment.

12.3: Passing File Stream Objects to Functions in C++ 11319

Question

Write the definition of a function named  openLog . This function can be safely passed two arguments, an  fstream object and a  string object. The function associates the  fstream with a file whose name is formed by concatenating the second argument with the suffix ".log". The  fstream is made ready for output that is appended to the end of the file. If the file did not exist previously, false is returned; otherwise its content is deleted (truncated) and replaced by a single line:
    PREVIOUS CONTENT DELETED
and true is returned.

Solution
If you have a solution, please send via comment

12.2: File Output Formatting: 11308

Question

Given three variables, k, m, n, of type int that have already been declared and initialized, write some code that prints each of them left-justified in a 9-position field on the same line. For example, if their values were 27, 987654321, -4321, the output would be:

|27xxxxxxx987654321-4321xxxx

NOTE: The vertical bar,  | , on the left above represents the left edge of the print area; it is not to be printed out. Also, we show x in the output above to represent spaces-- your output should not actually have x's!

Solution
cout.setf(ios::left, ios::adjustfield);
cout << setw(9) << k << setw(9) << m << setw(9) << n;

12.2: File Output Formatting: 11304

Question

Given three variables, a, b, c, of type double that have already been declared and initialized, write a statement that prints each of them on the same line, separated by one space, in such away that scientific (or e-notation or exponential notation) is avoided. Each number should be printed with 5 digits to the right of the decimal point. For example, if their values were 4.014268319, 14309, 0.00937608, the output would be:

|4.01427x14309.00000x0.00938

NOTE: The vertical bar,  | , on the left above represents the left edge of the print area; it is not to be printed out. Also, we show x in the output above to represent spaces-- your output should not actually have x's!

Solution
cout << setprecision(5);
cout << fixed << a << " " << b << " " << c << " ";

12.1: File Operations: 11314

Question

Given an  ifstream object named  input , associate it with a file named  hostdata by opening the file for input.

Solution
input.open("hostdata",ios::in);

12.1: File Operations: 11313

Question

Given an  fstream object named  menu , associate it with a file named  todaysmenu.txt for output in a way that truncates (erases) any existing data in the file.

Solution
menu.open("todaysmenu.txt",ios::out);

12.1: File Operations: 11312

Question

Given an  fstream object named  todo , associate it with a file named  todolist by opening the file for appending.

Solution
todo.open("todolist");

12.1: File Operations: 11311

Question

Given an  ofstream object named  output , associate it with a file named  yearsummary.txt for output in a way that truncates (erases) any existing data in the file.

Solution
output.open("yearsummary.txt",ios::trunc);

11.6: Focus on Software Engineering: Nested Structures: 10752

11.6: Focus on Software Engineering: Nested Structures: 10752
Question

Assume that  SREC has already been defined. Define a new type,  ROSTER , that is a structure consisting of an  int field,  size , and another field,  grades , that is an  SREC array with 500 elements.

Solution
struct ROSTER
{
    int size;
    SREC grades[500];
};

11.3: Accessing Structure Members: 11153

Question

Assume you are given a variable, payRate of type Money (a structured type with two int fields, dollars and cents). Write the necessary code to increase the effective value of payRate by $1.50. To do this you need to add 50 to cents and 1 to dollars but you ALSO must make sure that cents does not end up over 99: if it does, you need to "carry a one" to dollars. For example, if payRate were $12.80 then a naive addition of $1.50 yields 13 (dollars) and 130 (cents). This would have to be changed to 14 (dollars) and 30 (cents).

Solution
Money payRateIncrease;
payRateIncrease.dollars=1;
payRateIncrease.cents=50;

payRate.dollars += payRateIncrease.dollars + (payRate.cents + payRateIncrease.cents)/100;
payRate.cents = (payRate.cents + payRateIncrease.cents) % 100;

11.3: Accessing Structure Members: 11002

Question

The "origin" of the cartesian plane in math is the point where x and y are both zero. Given a variable, origin of type Point-- a structured type with two fields, x and y, both of type double, write one or two statements that make this variable's field's values consistent with the mathematical notion of "origin".

Solution
origin.x=0.0;
origin.y=0.0;

11.2: Focus on Software Engineering: Combining Data into Structures: 11055

Question

Declare a structure whose tag name is Server and that contains the following fields: manufacturer, a string, model and serialnum, both also strings, year, an int, clockSpeed, a double, cores, an int, ram, an int and finally storage an int.

Solution
struct Server
{
    string manufacturer, model, serialnum;
    int year;
    double clockSpeed;
    int cores, ram, storage;
};

11.2: Focus on Software Engineering: Combining Data into Structures: 10976

Question

Declare a structure whose tag name is Book and that contains exactly three fields (or members), each of type int. The first field is nCopies, the second field is nPages and the third field is nAuthors.

Solution
struct Book
{
    int nCopies, nPages, nAuthors;
};

11.2: Focus on Software Engineering: Combining Data into Structures: 11005

Question

Given the declaration of a structure whose tag is DATE write the declaration of the following variables enrolled_on, paid_on, and completed_on, each of which is of type DATE.

Solution
DATE enrolled_on, paid_on, completed_on;

CH10: Programming Challenge #18

Question

10.18: Phone Number List
Write a program that has an array of at least 50 string objects that hold people’s names and phone numbers. The program then reads lines of text from a file named phonebook  into the array.

The program should ask the user to enter a name or partial name to search for in the array. All entries in the array that match the string entered should be displayed-- thus there may be more than one entry displayed.

Prompts And Output Labels. The program prints the message "Enter a name or partial name to search for: " and then after the user enters a some input and hits return, the program skips a line, and prints the heading: "Here are the results of the search:", followed by each matched string in the array on a line by itself.

Input Validation. None.

Solution (Raezorane R.)


#include 
#include 
#include 
using namespace std;

int main()
{
const int SIZE = 50;
string phoneDirectory[SIZE];
int size=0;
string name; //name to look for

ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail()) {
getline(inFile,phoneDirectory[size]);
size++;
}
inFile.close();

// Get a name or partial name to search for.
cout << "Enter a name or partial name to search for: ";
getline(cin, name);

cout << "\nHere are the results of the search: " << endl;
int numberEntriesFound = 0;

for (int k = 0; k < size; k++)
{
if (phoneDirectory[k].find(name.data(), 0) < phoneDirectory[k].length())
{
numberEntriesFound ++;
cout << phoneDirectory[k] << endl;
}
}
if (numberEntriesFound == 0)
cout << "\nNo Entries were found for " << name;
return 0;


}

CH10: Programming Challenge #15

Question

10.15: Character Analysis
Write a program that reads the contents of a file named text.txt and determines the following:
The number of uppercase letters in the file
The number of lowercase letters in the file
The number of digits in the file

Prompts And Output Labels. There are no prompts-- nothing is read from standard in, just from the file text.txt. Each of the numbers calculated is displayed on a separate line on standard output, preceded by the following prompts (respectively): "Uppercase characters: ", "Lowercase characters: ", "Digits: ".

Input Validation. None.

Solution (By Raezorane R.)

// Chapter 10, Programming Challenge 15: Character Analysis
#include 
#include 
using namespace std;

int main()
{
char ch; // To hold a character from the file

// Counters for the number of uppercase characters,
// lowercase characters, and digits found in the file.
int uppercase = 0;
int lowercase = 0;
int digits = 0;

// Open the file.
ifstream inputFile;
inputFile.open("text.txt");

// Read each character in the file
// and analyze it.
while (inputFile >> ch)
{
if (isupper(ch))
uppercase++;

if (islower(ch))
lowercase++;

if (isdigit(ch))
digits++;
}

// Close the file.
inputFile.close();

// Display the results.
cout << "Uppercase characters: " << uppercase << endl;
cout << "Lowercase characters: " << lowercase << endl;
cout << "Digits: " << digits << endl;

return 0;


10.7: More about the C++ string Class: 10864

Question

Assume that  word is a variable of type  string that has been assigned a value. Assume furthermore that this value always contains the letters "dr" followed by at least two other letters. For example: "undramatic", "dreck", "android", "no-drip".

Assume that there is another variable declared,  drWord , also of type  string . Write the statements needed so that the 4-character substring word of the value of  word starting with "dr" is assigned to  drWord . So, if the value of  word were "George slew the dragon" your code would assign the value "drag" to  drWord .

Solution
drWord = word.substr(word.find("dr"),4);

10.7: More about the C++ string Class: 10847

Question

Assume that  name is a variable of type  string that has been assigned a value. Write an expression whose value is the first character of the value of  name . So if the value of  name were "Smith" the expression's value would be 'S'.

Solution
name[0]

10.4: Library Functions for Working with C-Strings: 10714

Question

Write a function  max that has two C string parameters and returns the larger of the two.

Solution
char* max(char *a, char *b)
{
    int result = strcmp(a, b);

    if (result > 0)
        return a;
    else
        return b;
}

10.4: Library Functions for Working with C-Strings: 10713

Question

Given the  char * variables  name1 ,  name2 , and  name3 , write a fragment of code that assigns the largest value to the variable  max (assume all three have already been declared and have been assigned values).

Solution
max=name1;
if (strcmp(name2, max)>0)
    max=name2;

if (strcmp(name3,max)>0)
    max=name3;

10.3: C-Strings: 10900

Question

Assume that scotus is a two-dimensional character array that stores the family names (last names) of the nine justices on the Supreme Court of the United States. Assume no name is longer than twenty characters. Assume that scotus has been initialized in alphabetical order. Write an expression whose value is the last name stored in the array.

Solution
scotus[8]

10.3: C-Strings: 11122

Question

Declare a char array named  line suitable for storing C-strings as large as 50 characters, and write a statement that reads in the next line of standard input into this array. (Assume no line of input is 50 or more characters.)

Solution
char line[50];
cin.getline(line,50);

8.1: Focus on Software Engineering: Introduction to Search Algorithms: 60250

Question
   
CodeLab is
a) an IDE (integrated development environment)
b) an AI-based intelligent tutoring system
c) an online set of interactive exercises with immediate feedback
d) software testing system

Solution
c) an online set of interactive exercises with immediate feedback

7.7: Arrays as Function Arguments: 10652


Question

Write a statement that declares a prototype for a function  printArray , which has two parameters. The first parameter is an array of element type  int and the second is an  int , the number of elements in the array. The function does not return a value.

Solution
void printArray(int [], int);

MPL Extra: Composition: 10802

Question

Assume that x is a variable that has been declared as an int and been given a value. Assume that twice is a function that receives a single integer parameter and returns twice its value. (So if you pass 7 to twice it will return 14. Thus the expression twice(7) has the value 14.

Write an expression whose value is eight times that of x without using the standard C arithmetic operators (*,+, etc.). Instead, use calls to twice to accomplish this.

In this exercise you must write this as a single expression-- you must not write any statements. Also, you may only use the twice() function-- no other functions or operators.

Solution
twice(twice(twice(x)))

MPL Extra: Composition: 10778

Question

Assume the availability of a function named  oneMore . This function receives an integer and returns one more than its parameter. So, pass  oneMore(12 ) and it will return 13. DO NOT DEFINE this function-- just assume it is available. YOUR TASK: write an expression whose value is 5 but in your expression you can only use the integer literal 0. You can not use anything with the digits 1-9 and you cannot use any arithmetic operators like +-*/. But you can use 0 and you can make calls to the function oneMore.

Solution
oneMore(oneMore(oneMore(oneMore(oneMore(0)))))

5.6: the for Loop: 10971

Question

Write a for loop that prints the integers 1 through 40, separated by spaces or new lines.  You may use only one variable, count which has already been declared as an integer.

Solution (By Travis N)

for (count=1; count<41; count++)
{
   count << count << " ";
}