Rédigé par des étudiants ayant réussi Disponible immédiatement après paiement Lire en ligne ou en PDF Mauvais document ? Échangez-le gratuitement 4,6 TrustPilot
logo-home
Examen

Exam (elaborations) TEST BANK FOR Beginning C++ Through Game Programming 2nd Edition By Michael Dawson (Instructor Solution Manual)

Note
-
Vendu
-
Pages
68
Grade
A+
Publié le
07-11-2021
Écrit en
2021/2022

Exam (elaborations) TEST BANK FOR Beginning C++ Through Game Programming 2nd Edition By Michael Dawson (Instructor Solution Manual) Beginning C++ Game Programming Chapter Discussion Question and Exercise Solutions Chapter 1 Discussion Questions 1. How does having a widely adopted C++ standard help game programmers? Solution: Having a widely adopted standard helps game programmers in several ways. First, it helps to ensure consistency among compilers—this means that the same program, written to the standard, should compile successfully across multiple compilers that implement the standard. Second, the standard makes it easier to write cross-platform code—code written to the standard should compile and work correctly across different operating systems (again, given compilers that faithfully implement the standard). Third, it helps ensure that multiple programmers can work more seamlessly together—if both are writing to the standard their code should have fewer conflicts. 2. What are the advantages and disadvantages of employing the using directive? Solution: The major advantage of a employing the using directive is that it saves typing. If a programmer puts using namespace std; in his program, he saves having to prefix every element in the namespace std with std::. One could also argue that removing all of the std:: references from a program makes it less cluttered and easier to read. A disadvantage of employing a using directive is that it may not be clear where different objects and functions originate—what namespace they‘re from. Another disadvantage with employing a using directive is that you run the risk of name conflicts. For example, if you employed the using directive for two namespaces that had elements with the same name, there would be a name conflict. This, of course, is the very thing that namespaces were created to prevent. 3. Why might you define a new name for an existing type? Solution: You might define a new name for an existing type if you simply wanted a shorter name for a type that you use often in a program. For example, you might do something like: typedef unsigned short int ushort; so that you can use the concise ushort instead of the much longer unsigned short int. But you could also argue that the name a programmer creates for an existing type might be clearer than the syntax for the existing type. For example, ushort might scan better than the longer unsigned short int. 4. Why are there two versions of the increment operator? What‘s the difference between them? Solution: Both versions of the increment operator increment a variable, but there‘s a subtle and important difference in the way the two operators work. The prefix increment operator is placed before the variable to be incremented, as in ++score, while the postfix increment operator is placed after the variable to be incremented, as in score++. The prefix increment operator increments a variable before the evaluation of a larger expression involving the variable while the postfix increment operator increments a variable after the evaluation of a larger expression involving the variable. 5. How can you use constants to improve your code? Solution: Constants can provide two important benefits. First, they can make programs clearer. MAX_HEALTH more clearly conveys the intention of a value than some literal, like say 100. Second, constants make changes easier. If you want to change the value of a constant, you only need to make a change in one place: where it was defined. If you used the same literal value throughout a program, you‘d have to change that literal everywhere (while making sure not to change the literal value where it‘s not related to the constant value). Exercises 1. Create a list of six legal variable names -- three good and three bad choices. Explain why each name falls into the good or bad category. Solution: Responses will vary, but the following is a set of possible answers: Good Names health A clear, short name numEnemies Clear that variable represents a number; descriptive isGameOver Clear that variable represents a bool Bad Names HeAlTh While it‘s legal to used a mixed-case name, it‘s unconventional and distracting TotalNumberofCurrentEnemies While it may be clear, the name is cumbersome; there must be a shorter, yet-still-clear name igo Short but not clear; a little more typing may be worthwhile for the sake of clarity 2. What‘s displayed by each line in the following code snippet? Explain each result. cout "Seven divided by three is " 7 / 3 endl; cout "Seven divided by three is " 7.0 / 3 endl; cout "Seven divided by three is " 7.0 / 3.0 endl; Solution: cout "Seven divided by three is " 7 / 3 endl; displays 2. That‘s because both numbers in the expression 7 / 3 are integers, making the operation integer division, which always results in an integer. cout "Seven divided by three is " 7.0 / 3 endl; displays 2.33333. That‘s because at least one number in the expression 7.0 / 3 is a floating point number. A division operation with at least one floating point number yields a floating point result. cout "Seven divided by three is " 7.0 / 3.0 endl; displays 2.33333. That‘s because at least one number in the expression 7.0 / 3.0 is a floating point number. A division operation with at least one floating point number yields a floating point result. 3. Write a program that gets three game scores from the user and displays the average. Solution: The source code is in the file bcppgp_solutionssourcechap01chap01_. Chapter 2 Exercises 1. Rewrite the Menu Chooser program from this chapter using an enumeration to represent difficulty levels. Solution: The source code is in the file bcppgp_solutionssourcechap02chap02_. 2. What‘s wrong with the following loop? int x = 0; while (x) { ++x; cout x endl; } Solution: The problem is that since x is set to 0 just before the loop, the loop will never be entered—it may as well not exist in the program. A student might say that the loop, if entered, would be infinite, but that‘s not necessarily true. If x were initialized with a negative value, it would eventually be incremented to 0, at which point the loop would end. 3. Write a new version of the Guess My Number program in which the player and the computer switch roles. That is, the player picks a number and the computer must guess what it is. Solution: The source code is in the file bcppgp_solutionssourcechap02chap02_. Chapter 3 Discussion Questions 1. What are some of the things from your favorite game that you could represent as objects? What might their data members and member functions be? Solution Responses will vary, but the following is a set of possible answers: Ogre Data Members position speed health Methods Move() Attack() Die() Sword Data Members damage weight price Methods Swing() 2. What are the advantages of using an array over a group of individual variables? Solution: While you could represent a set of values with individual variables, using an array has advantages – especially if the values are related and will need to have the same operations applied to them. Using an array allows you to easily iterate through a set of values instead of being forced to access a group of individual variables. For example, if you wanted to represent a set of 10 high scores with individual variables, you‘d have to send each variable to cout to display all of the values, as in: cout "High Scores"; cout score1; cout score2; cout score3; cout score4; cout score5; cout score6; cout score7; cout score8; cout score9; cout score10; But using an array allows a shorter and more elegant solution: for (int i = 0; i numScores; ++i) cout score[i] endl; 3. What are some limitations imposed by a fixed array size? Solution: The major limitation imposed by a fixed array is that it can‘t grow in size. Once you establish the number of elements for the array, you can‘t change it. So, as a game programmer, you‘re forced to know the largest possible number of elements you will need to store with an array. Another disadvantage is that a fixed array can‘t shrink in size. Once you declare an array of a certain size, the memory needed to store all of the values in the array is allocated, even if only a few values are actually ever stored in the array as elements. 4. What are the advantages and disadvantages of operator overloading? Solution: An advantage of operator overloading is that using operators we already know with new types can be clear and require no special explanation. For example, using the + operator with the string objects intuitively represents the concatenation (the adding) of two strings. A disadvantage of operator overloading is that a programmer may feel that the use of an operator is clear when it isn‘t to most other programmers. 5. What kinds of games could you create using string objects, arrays, and for loops as your main tools? Solution: Responses will vary, but the following is a set of possible answers: Hangman A player gets a certain number of tries to guess the letters in a word, if he fails to guess in time, he loses and is hanged Antonyms A player is given a word and must supply its opposite Cryptograms A player is given an encrypted message where each letter in the message is substituted with a different letter from the alphabet Exercises 1. Improve the Word Jumble game by adding a scoring system. Make the point value for a word based on its length. Deduct points if the player asks for a hint. Solution: The source code is in the file bcppgp_solutionssourcechap03chap03_. 2. What‘s wrong with the following code? for (int i = 0; i = (); ++i) cout "Character at position " i " is: " phrase[i] endl; Solution: Given that phrase is a string variable, the final iteration of the loop attempts to access an element beyond the last character of phrase. This could lead to disastrous results, including a program crash. The loop attempts to access this nonexistent character because the test of the loop, i = (), is true when i is equal to (). The problem is that the valid element positions of phrase range from 0 to () – 1. 3. What‘s wrong with the following code? const int ROWS = 2; const int COLUMNS = 3; char board[COLUMNS][ROWS] = { {'O', 'X', 'O'}, {' ', 'X', 'X'} }; Solution: The code will fail to compile with an message such as, ―error: too many intializers for ‗char[2]‘.‖ This happens because the code declares an array 2x3 and tries to initialize its elements with data in a 3x2 grid. The initialization attempts to set values for array elements that don‘t exist. The corrected code is: const int ROWS = 2; const int COLUMNS = 3; char board[ROWS][COLUMNS] = { {'O', 'X', 'O'}, {' ', 'X', 'X'} }; Chapter 4 Discussion Questions 1. Why should a game programmer use the STL? Solution: The STL gives a game programmer a tested and honed set of useful containers, iterators and algorithms. This saves a game programmer the time and effort of creating his own data structures and algorithms. Even better, it saves a game programmer from spending time and effort writing less efficient data structures and algorithms. Now, there are occasions when a game programmer might not use the STL. For example, if there are unique requirements for working with collections of objects that are best met by a custom data structure. In addition, the STL imposes some extra memory requirements that might make it less attractive for some game consoles. It‘s also possible that on unique platforms, such as some game consoles, the STL might not be as mature as it is on the PC. But overall, the STL should be the first place a game programmer looks to meet all of his data structure needs. 2. What are the advantages of a vector over an array? Solution: The main advantage of a vector is that it is dynamic: it can grow or shrink as needed. This can result in a huge memory savings. With an array, a game programmer has to acquire all the memory necessary for the maximum number of elements he expects the array to ever hold during any run of the program -- and that memory is captured by the program regardless of how little the program actually needs for the elements. Conversely, the vector can use only the memory required by the number of elements that needs to be stored in it. With a vector, a game programmer doesn't have to know the maximum number of elements he'll need to store ahead of time. Another advantage is that a vector can be manipulated with many of the STL algorithms. So it's like the game programmer gets commonly used algorithms for free. Vectors do require a little more memory than arrays, but this tradeoff is almost always worth the benefits. 3. What types of game objects might you store with a vector? Solution: You can store any collection of game objects with a vector, but the best use of this container is for game objects that make up a sequence. Of course, the vector can be used for random access based on a position number as well. A vector could be used to store all kinds of game objects. Here are just a few examples: a player‘s inventory, a list of weapons a player can cycle through, a list of high scores and a list of all the players in a multiplayer game. 4. How do performance characteristics of a container type affect the decision to use it? Solution: Understanding the performance of a container along with how you plan to use the container are critical in deciding which container from the STL best suits your needs. Different container types have different performance properties. They‘re like tools in a toolbox; each tool is best suited for a different job. As an example, let's look at vectors and lists. Lists and vectors are two different types of sequence containers, each with their own performance characteristics. With lists, inserting and erasing elements takes the same amount of time no matter where in the sequence you insert or delete. This is not the case with vectors because inserting or deleting an element in the middle of a vector requires all of the elements after the insertion or deletion point to be moved. However, vectors are faster when it comes to adding or deleting an element at the end of a sequence. Vectors are also faster to traverse than lists. So, if a game programmer needs to represent a sequence of objects and he knows that he will rarely insert into or delete from the middle of the sequence, a vector is probably his best bet. But, if the game programmer knows that he will have a large sequence and plans to do a lot of insertion and deletion in the middle of that sequence, a list may be his best choice. 5. Why is program planning important? Solution: Planning your programs will almost always result in time and frustration saved. Programming is a lot like construction. If a contractor were to build a house for you without a blueprint, you might end up with a house that has 12 bathrooms, no windows, and a front door on the second floor. Plus, it probably would cost you 10 times the estimated price. Programming is the same way. Without a plan, you‘ll likely struggle through the process and waste time. You might even end up with a program that doesn‘t quite work or a program that is difficult to modify. Exercises 1. Write a program using vectors and iterators that allows a user to maintain a list of his or her favorite games. The program should allow the user to list all game titles, add a

Montrer plus Lire moins
Établissement
Cours

Aperçu du contenu

, Beginning C++ Game Programming
Chapter Discussion Question and Exercise Solutions

Chapter 1

Discussion Questions

1. How does having a widely adopted C++ standard help game programmers?

Solution:
Having a widely adopted standard helps game programmers in several ways. First, it
helps to ensure consistency among compilers—this means that the same program, written
to the standard, should compile successfully across multiple compilers that implement the
standard. Second, the standard makes it easier to write cross-platform code—code
written to the standard should compile and work correctly across different operating
systems (again, given compilers that faithfully implement the standard). Third, it helps
ensure that multiple programmers can work more seamlessly together—if both are
writing to the standard their code should have fewer conflicts.


2. What are the advantages and disadvantages of employing the using directive?

Solution:
The major advantage of a employing the using directive is that it saves typing. If a
programmer puts using namespace std; in his program, he saves having to prefix every
element in the namespace std with std::. One could also argue that removing all of the
std:: references from a program makes it less cluttered and easier to read. A
disadvantage of employing a using directive is that it may not be clear where different
objects and functions originate—what namespace they‘re from. Another disadvantage
with employing a using directive is that you run the risk of name conflicts. For example,
if you employed the using directive for two namespaces that had elements with the same
name, there would be a name conflict. This, of course, is the very thing that namespaces
were created to prevent.


3. Why might you define a new name for an existing type?

Solution:
You might define a new name for an existing type if you simply wanted a shorter name
for a type that you use often in a program. For example, you might do something like:
typedef unsigned short int ushort;


so that you can use the concise ushort instead of the much longer unsigned short int.
But you could also argue that the name a programmer creates for an existing type might
be clearer than the syntax for the existing type. For example, ushort might scan better
than the longer unsigned short int.

,4. Why are there two versions of the increment operator? What‘s the difference
between them?

Solution:
Both versions of the increment operator increment a variable, but there‘s a subtle and
important difference in the way the two operators work. The prefix increment operator is
placed before the variable to be incremented, as in ++score, while the postfix increment
operator is placed after the variable to be incremented, as in score++. The prefix
increment operator increments a variable before the evaluation of a larger expression
involving the variable while the postfix increment operator increments a variable after the
evaluation of a larger expression involving the variable.


5. How can you use constants to improve your code?

Solution:
Constants can provide two important benefits. First, they can make programs clearer.
MAX_HEALTH more clearly conveys the intention of a value than some literal, like say 100.
Second, constants make changes easier. If you want to change the value of a constant,
you only need to make a change in one place: where it was defined. If you used the same
literal value throughout a program, you‘d have to change that literal everywhere (while
making sure not to change the literal value where it‘s not related to the constant value).


Exercises

1. Create a list of six legal variable names -- three good and three bad choices. Explain
why each name falls into the good or bad category.

Solution:
Responses will vary, but the following is a set of possible answers:

Good Names
health A clear, short name
numEnemies Clear that variable represents a number; descriptive
isGameOver Clear that variable represents a bool

Bad Names
HeAlTh While it‘s legal to used a mixed-case name, it‘s
unconventional and distracting
TotalNumberofCurrentEnemies While it may be clear, the name is cumbersome;
there must be a shorter, yet-still-clear name
igo Short but not clear; a little more typing may be
worthwhile for the sake of clarity

, 2. What‘s displayed by each line in the following code snippet? Explain each result.
cout << "Seven divided by three is " << << endl;
cout << "Seven divided by three is " << 7. << endl;
cout << "Seven divided by three is " << 7..0 << endl;


Solution:
cout << "Seven divided by three is " << << endl; displays 2. That‘s because
both numbers in the expression 7 / 3 are integers, making the operation integer division,
which always results in an integer.

cout << "Seven divided by three is " << 7. << endl; displays 2.33333. That‘s
because at least one number in the expression 7. is a floating point number. A
division operation with at least one floating point number yields a floating point result.

cout << "Seven divided by three is " << 7..0 << endl; displays 2.33333.
That‘s because at least one number in the expression 7..0 is a floating point
number. A division operation with at least one floating point number yields a floating
point result.


3. Write a program that gets three game scores from the user and displays the average.

Solution:
The source code is in the file bcppgp_solutions\source\chap01\chap01_exercise03.cpp.


Chapter 2

Exercises

1. Rewrite the Menu Chooser program from this chapter using an enumeration to
represent difficulty levels.

Solution:
The source code is in the file bcppgp_solutions\source\chap02\chap02_exercise01.cpp.



2. What‘s wrong with the following loop?
int x = 0;
while (x)
{
++x;
cout << x << endl;

Livre connecté

École, étude et sujet

Établissement
Cours

Infos sur le Document

Publié le
7 novembre 2021
Nombre de pages
68
Écrit en
2021/2022
Type
Examen
Contient
Questions et réponses

Sujets

€13,02
Accéder à l'intégralité du document:

Mauvais document ? Échangez-le gratuitement Dans les 14 jours suivant votre achat et avant le téléchargement, vous pouvez choisir un autre document. Vous pouvez simplement dépenser le montant à nouveau.
Rédigé par des étudiants ayant réussi
Disponible immédiatement après paiement
Lire en ligne ou en PDF

Faites connaissance avec le vendeur

Seller avatar
Les scores de réputation sont basés sur le nombre de documents qu'un vendeur a vendus contre paiement ainsi que sur les avis qu'il a reçu pour ces documents. Il y a trois niveaux: Bronze, Argent et Or. Plus la réputation est bonne, plus vous pouvez faire confiance sur la qualité du travail des vendeurs.
Expert001 Chamberlain School Of Nursing
S'abonner Vous devez être connecté afin de suivre les étudiants ou les cours
Vendu
816
Membre depuis
4 année
Nombre de followers
566
Documents
1173
Dernière vente
1 jours de cela
Expert001

High quality, well written Test Banks, Guides, Solution Manuals and Exams to enhance your learning potential and take your grades to new heights. Kindly leave a review and suggestions. We do take pride in our high-quality services and we are always ready to support all clients.

4,1

162 revues

5
105
4
18
3
14
2
8
1
17

Documents populaires

Récemment consulté par vous

Pourquoi les étudiants choisissent Stuvia

Créé par d'autres étudiants, vérifié par les avis

Une qualité sur laquelle compter : rédigé par des étudiants qui ont réussi et évalué par d'autres qui ont utilisé ce document.

Le document ne convient pas ? Choisis un autre document

Aucun souci ! Tu peux sélectionner directement un autre document qui correspond mieux à ce que tu cherches.

Paye comme tu veux, apprends aussitôt

Aucun abonnement, aucun engagement. Paye selon tes habitudes par carte de crédit et télécharge ton document PDF instantanément.

Student with book image

“Acheté, téléchargé et réussi. C'est aussi simple que ça.”

Alisha Student

Foire aux questions