Tải bản đầy đủ (.pdf) (23 trang)

C++ Programming for Games Module I phần 3 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (471.45 KB, 23 trang )

An if…else statement can branch execution along two separate paths—one path if the condition is true
ever, what if you need more than two execution paths?
at if you wanted to say: “if A then B else, if C then D else, if E then F else G.” This can
achi eral nested if…else statements. Program 2.6 shows how this might be used to
g-type game based on the character the user
ogram …else statements.
or a second path if the condition is not true. How
F
e
or instance, wh
b eved by using sev
initialize a player’s character class in a fantasy role-playin
selected.

Pr 2.6: Program illustrates creating multiple execution paths using nested if
#include <iostream>
#include <string>
using namespace std;

int main()
{
// Output some text asking the user to make a selection.
cout << "Welcome to Text-RPG 1.0" << endl;
cout << "Please select a character class number "<< endl;
cout << "1)Fighter 2)Wizard 3)Cleric 4)Thief : ";

// Prompt the user to make a selection.
int characterNum = 1;
cin >> characterNum;

// Initialize character variables to default value.


int numHitpoints = 0;
int numMagicPoints = 0;
string weaponName = "";
string className = "";

if( characterNum == 1 ) // Fighter selected?
{
numHitpoints = 10;
numMagicPoints = 4;
weaponName = "Sword";
className = "Fighter";
}
else if( characterNum == 2 ) // Wizard selected?
{
numHitpoints = 4;
numMagicPoints = 10;
weaponName = "Magic Staff";
className = "Wizard";
}
else if( characterNum == 3 ) // Cleric selected?
{
numHitpoints = 7;
numMagicPoints = 7;
weaponName = "Magic Staff";
className = "Cleric";
}
else // Not 1, 2, or 3, so select thief.
{
numHitpoints = 8;
numMagicPoints = 6;


52
weaponName = "Short Sword";
className = "Thief";
}

cout << endl;
cout << "Character properties:" << endl;
co < "Class name = " << className ut < << endl;
cout << "Hitpoints = " << numHitpoints << endl;
cout << "Magicpoints = " << numMagicPoints << endl;
co < "Weapon = " << weaponName ut < << endl;
}

Output 2.6.
Welcome to Text-RPG 1.0
Please select a character class number
1)Fighter 2)Wizard 3)Cleric 4)Thief : 2

Character properties:
Class name = Wizard
Hitpoints = 4
Magicpoints = 10
Weapon = Magic Staff
Press any key to continue

Here we provide four different execution paths based on whether the user chose a “Fighter,” “Wizard,”
“Cleric,” or “Thief.” Adding more execution paths is trivial. You need only add more “else if”
statements in the pattern shown.


2.3.4 The Switch Statement
The switch statement is essentially a cleaner alternative to nested if…else statements. It is best
explained by example, so consider the following:

rogram 2.7: Program illustrates creating multiple execution paths using the switch statement. P
#include <iostream>
#include <string>
using namespace std;

int main()
{
int num = 0;
cout << "Enter an even integer in the range [2, 8]: ";
cin >> num;

switch( num )
{
case 2:

53
cout << "Case 2 executed!" << endl;
break;
ca : se 4
cout << "Case 4 executed!" << endl;
break;
case 6:
cout << "Case 6 executed!" << endl;
break;
ca : se 8
cout << "Case 8 executed!" << endl;

break;
default:
cout << "Default case executed implies you do not ";
cout << "enter a 2, 4, 6, or 8." << endl;
break;
}
}

Output 2.7.
Enter an even integer in the range [2, 8]: 4
Case 4 executed!
Press any key to continue

Here
num is the value to test against several possible cases. The code first compares num against the first
case 2. If num equals 2 then the code following case 2 is executed; otherwise, the code jumps to the
next case—
case 4. If num equals 4 then the code following case 4 is executed; otherwise, the code
jumps to the next case, and so on. The
case is used to handle any other case not specifically
handled
equals 5, there is no case statement to handle the
case wh
se handles it.

p break statement is necessary following your case
a case handler and there is not an ending
break
o the next case handler, and then the next and so on
ncountered. The break statement

essentia ly exi the switch statement, which is typically desired after a particular case was
andled. To illustrate, Program 2.8 shows what happens if you do not include a
break statement.

ent with no “breaks.”
default
in the switch statement. For example, if
num
, so therefore the default ca
ere
num is 5
An im ortant f tatement is that a act about the switch s
handling code. When the execution flows into
flow automatically falls tstatement, the program
til th end un e of the default case handler, or until a
break is e
l ts out of
h
Program 2.8: Program demonstrates a switch statem
#include <iostream>
#include <string>
using namespace std;

int main()
{
int num = 0;
cout << "Enter an even integer in the range [2, 8]: ";
cin >> num;

switch( num )


54
{
case 2:
cout << "Case 2 executed!" << endl;
case 4:
cout << "Case 4 executed!" << endl;
case 6:
cout << "Case 6 executed!" << endl;
case 8:
cout << "Case 8 executed!" << endl;
default:
cout << "Default case executed implies you do not ";
cout << "enter a 2, 4, 6, or 8." << endl;
}
}

Output 2.8.
Enter an even integer in the range [2, 8]: 4
Case 4 executed!
Case 6 executed!
Case 8 executed!
Default case executed implies you do not enter a 2, 4, 6, or 8.
Press any key to continue

On the other hand, this execution fall-through may be used for your own purposes. For example, you
break;
case 3: // Fall through to case 4
case 4: // Fall through to case 5
e same code for 3, 4, and 5.



break;

.3.5 The Ternary Operator
ompact notation to represent a basic if…else statement. It is the only operator
rands. The general syntax is this:
ator:
might have a situation where you want to execute the same code for several cases. This can be
implemented like so:

case 0: // Fall through to case 1
case 1: // Fall through to case 2
case 2:
// Execute same code for 0, 1, and 2.
case 5:
// Execut
2
The ternary operator is a c
C++ that takes three opein

nary OperTer
(boolExpression ? value1 : value2)


55
The ternary operator may be read as follows. If
boolExpression is true then the ternary operation
valuates to
value1, else it evaluates to value2. Consider this specific example, where B is of type


10 : -5;
xpression evaluates to 10, which is then assigned to x. However, if B is not true
aluates to –5, which is then assigned to x. Notice that this is equivalent to:
;
ause of its cryptic
2.4 Repetition
The ab
will ne
enemy projectile” or “While the player is not dead, continue game play.” C++ facilitates the need for
petition via loops. C++ provides three different loop styles; these variations are for convenience
onl
three d

2. 1
The fo
The fol
Pro m
e
bool:

int x = B ?

If B is true then the e
then the expression ev

int x;
if( B )
x = 10
else

x = -5;


Finally, it is worth mentioning that many programmers dislike the ternary operator bec
ntax. sy

ility to repeat C++ statements is an important one. For instance, to make nontrivial programs we
ed to be able to say things like “For each game character, test whether or not any were hit by an
re
y—you could use only one of these styles and forever ignore the other two. However, by providing
ifferent styles, you can pick the style that is most natural to the type of repetition needed.
4. The for-loop
r-loop is commonly used when you need to repeat some statement(s) a known number of times.
lowing program executes an output statement ten times.

gra 2.9: Program demonstrates the for-loop.
#include <iostream>
using namespace std;

int main()
{
for(int cnt = 0; cnt < 10; ++cnt)
{
cout << cnt << ": Hello, World!" << endl;
}

56
}

Output 2.9.

0: Hello, World!
1: Hello, World!
2: Hello, World!
3: Hello, World!
4: Hello, World!
5: Hello, World!
6: Hello, World!
7: Hello, World!
8: Hello, World!
9: Hello, World!
Press any key to continue

The syntax of the for-loop is simple. There are essentially four parts to a “for loop.”
art 1; Part 2; Part 3)

for(P
{
art 4; P

}


Part 1: This can be any C++ statement(s). However, it is usually used to initialize a counting
variable; that is, a variable that counts the loop cycles. The code of Part 1 is executed first and
executed once. Program 2.9 declares and initializes a counting variable called
cnt to zero;
int cnt = 0.”
only
that is, “


• Part 2: This is the conditional part; that is, the loop continues to loop only so long as this
is condition is tested in every loop cycle. Program 2.9 makes the condition
uld continue to loop as long as the counting variable is less than ten; that is,
condition is true. Th
that the program sho

cnt < 10.”

• Part 3: This can be any C++ statement(s). However, it is usually used to modify the counting
y. The statement(s) of Part 3 are executed for every loop cycle. In Program
ounter variable so that cnt is increased by one for every loop cycle.
Because
cnt is initialized to zero and it is incremented by one for every loop cycle, it follows
variable in some wa
2.9, we increment the c
that Program 2.9’s for-loop will repeat exactly ten times.


Part 4: This part contains the statement(s) which you want to execute for every cycle of the loop.
Just as in an “if” statement, the curly braces are optional for one statement. However, if you need
to execute several statements per cycle then you need the curly braces to form a compound
statement.

, the following code is functionally equivalent to the for-loop of

int cnt = 0;
To show the flexibility of the for-loop
Program 2.9:

57

for( ; cnt < 10; )
{
cout << cnt << ": Hello, World!" << endl;
++cnt;
}


What we have done here is moved the counter initialization outside the loop and replaced Part 1 with an
mpty statement, which is perfectly legal since Part 1 can be “any C++ statement(s)”. Second, we have
rt 4, and we replaced Part 3 with an empty statement.
gal since Part 3 can be “any C++ statement(s)”. Convince yourself that this
2.9.
and Part 3 of the for-loop can contain multiple statements. For example:
e
moved the counter increment from Part 3 to Pa
Again, this is perfectly le
alternate for-loop is functionally equivalent to the for-loop of Program

Finally, Part 1

Program 2.10: Program demonstrates the for-loop.
#include <iostream>
us namespace std; ing
int main()
{
fo t cnt1 = 0, int cnt2 =r(in -cnt2) 9; cnt1 < 10; ++cnt1, -
{
cout << cnt1 << " Hello, World! " << cnt2 << endl;
}
}


Output 2.10.
0 Hello, World! 9
1 Hello, World! 8
2 Hello, World! 7
3 Hello, World! 6
4 Hello, World! 5
5 Hello, World! 4
6 Hello, World! 3
7 Hello, World! 2
8 Hello, World! 1
9 Hello, World! 0
Press any key to continue

This time there are two counter variables (separat
cremented and the oth
ed by commas), which are initialized to 0 and 9.
er is decremented. Consequently, as shown from the output,
ards. Part 2—the condition—remains the same; that is, it still
Moreover, one is in
one counts forward and one counts backw
e loop ten times. specifies that w

2.4.2 The while Loop

58
The while-loop is commonly used when you need to repeat some statements an unknown number of
mes. For example, in a poker game, after every hand, the program might ask the user if he wants to
ser input, the program will decide whether to “repeat” and play again, or to
ti

play again. Based on this u
exit the loop.

The following program illustrates a while-loop that terminates based on user input.

Program 2.11: Program demonstrates the while-loop.
#include <iostream>
using namespace std;

int main()
{
// Boolean value, true if we want to quit, false otherwise.
bool quit = false;

// Keep looping so long as quit is not true.
while( !quit )
{
// Ask the user if they want to quit or not.
char inputChar = 'n';
cout << "Continue to play? (y)es/(n)o ";
cin >> inputChar;

// Test for both uppercase or lowercase.
if( inputChar == 'n' || inputChar == 'N')
{
cout << "Exiting " << endl;
quit = true;
}
else
cout << "Playing game " << endl;

}
}

O .11. utput 2
Continue to play? (y)es/(n)o y
Playing game
Continue to play? (y)es/(n)o Y
Playing game
Continue to play? (y)es/(n)o y
Playing game
Continue to play? (y)es/(n)o n
Exiting
Press any key to continue

Program 2.11 is a useful example because, in addition to the while-loop, it demonstrates many of the
other topics of this chapter; namely, relational operators (e.g.,
inputChar == 'n'), logical operators
(e.g.,
!quit) and conditional statements (if…else).


59
As Program 2.11 implies, the while-loop takes on the following general syntax:
Execute this C++ statement(s);

The condition used in Program 2.11 is the boolean expression
!quit (not quit), which instructs the
s !quit is true. If the condition is true, we execute the statements in
the loop body. Inside the loop body, the program asks the user if he wishes to continue. If the player
chooses “no” then the program assigns true to quit, thereby making false. This will cause the

depends on user input.
ile Loop
o the while-loop. However, a do…while is guaranteed to execute at least
ce. these statements at least once regardless of the condition, then while the
nditi o do these statements.” Program 2.12 shows the do…while syntax.
ogram 2.12: P

while( condition is true )

program to keep looping so long a
!quit
while-loop to terminate on the next cycle when the condition
!quit is tested again. Observe that this
loop will repeat an unknown amount of times and its termination

2.4.3 The do…wh
The do…while loop is similar t
Essentially it says: “Do on
co on holds, continue t

Pr ro emonstrates the do…while lgram d oop.
#include <iostream>
using namespace std;
int main()
{
bool condition = false;

do
{
c < "Enter a 0 to quit or 1 to coout < ntinue: ";

cin >> condition;
}
while( condition );
}


Output 2.12.
Enter a 0 to quit or 1 to continue: 1
Enter a 0 to quit or 1 to continue: 1
Enter a 0 to quit or 1 to continue: 0
Press any key to continue

A
b
s you can see from Program 2.12, despite
condition being initialized to false, we still enter the loop
ody. Inside the body, the program assigns the truth-value the user entered to
condition. Then at the
end, the condition is tested to see if we will loop again. By moving the loop condition to the end, we are
guaranteed the loop body statements will be executed at least once.

60

Note that it does not take too much imagination to see how a do…while loop could be rewritten using a
while-loop. Consequently, in practice, the do…while loop is not encountered very often.

2.4.4 Nesting Loops
Just as if…else statements can be nested, loops can be nested; that is, a loop inside a loop. Consider the
following program, which nests a for-loop inside a while-loop:


Program 2.13: Program demonstrates nested loops; that is, loops inside loops.
#include <iostream>
using namespace std;

int main()
{
bool quit = false;

while( !quit )
{
for(int cnt = 0; cnt < 10; ++cnt)
cout << cnt << " ";

cout << endl;

char inputChar = 'n';
cout << "Print next ten integers (y)es/(n)o? ";
cin >> inputChar;

if(inputChar == 'n' || inputChar == 'N')
{
cout << "Exiting " << endl;
quit = true;
}
}
}
Output 2.13.
0 1 2 3 4 5 6 7 8 9
Print next ten integers (y)es/(n)o? y
0 1 2 3 4 5 6 7 8 9

Print next ten integers (y)es/(n)o? y
0 1 2 3 4 5 6 7 8 9
Print next ten integers (y)es/(n)o? n
Exiting
Press any key to continue


61
Here the outermost while-loop executes the innermost for-loop. The inner for-loop outputs the integers
, and -loop continues to loop as long as the user specifies to continue. Thus, rows of
user answers “yes” to the question.
p need to be handled which terminate the loop early. For example,
) over a set of game items until you find a specific one. However, once you find it,
ou can stop your search and exit the loop. To facilitate this case, C++ provides the
keyword,
which b
an infi
the play
gram 2.14: Program demonstrates the ‘break’ keyword. (Note that Program 2.14 has the same functionality as
Program 2.11 and therefore will have same output for the same input.)
0-9 the outer while
integers 0-9 will continue to be output as long as the
2.4.5 Break and Continue Keywords
Sometimes spec
u may iterate (loop
ial cases inside a loo
yo
y
break
reaks out of the current loop. To illustrate, Program 2.14 rewrites Program 2.11, this time using

nite loop; that is, a loop that is always true (and as such, will loop infinite times). This time, if
er chooses not to continue, a break statement is executed to exit the infinite loop.

Pro
#include <iostream>
using namespace std;

int main()
{
// Loop forever.
while( true )
{
// Ask the user if they want to quit or not.
char inputChar = 'n';
cout << "Continue to play? (y)es/(n)o ";
cin >> inputChar;

// Test for both uppercase or lowercase.
if( inputChar == 'n' || inputChar == 'N')
{
cout << "Exiting " << endl;
break; //< This will exit out of the infinite loop.
}
else
cout << "Playing game " << endl;
}
}
In addition to breaking out of a loop early, there may be special cases that allow us to decide early on
hether we can jump straight to the next loop cycle. The following program sums the numbers from
s this by testing for

o the next loop
w
zero to fifteen. However, it ignores the numbers three, seven, and thirteen. It doe
these numbers, and if it finds one of them, then the program simply continues (jumps) t
cycle, thereby ignoring them (i.e., not including them in the sum).

Program 2.15: Program demonstrates the ‘continue’ keyword. (Note that Program 2.15 does not output anything.)
#include <iostream>
using namespace std;


62
in in() t ma
{
int sum = 0;
for(int cnt = 0; cnt <= 15; ++cnt)
{
nt == 3 || cnt == 7 || cnt == 13) if( c
continue; // < jump straight to next loop cycle.

// Otherwise, add the number to the sum.
sum += cnt;
}
}

statements. However, in some cases, the
break and
continue keywords provide a much cleaner, shorter, and intuitive way of expressing the idea than a
more complex if…else statement would.
2.5 Arrays

hus fa e needed, we simply declared them like so:
“”;
owev 00 variables or an even greater amount? It is not practical to actually
d give them all unique names. We can, however, declare a set of variables
the act way using an array. An array is a contiguous block of memory that
vidual variables in an array the elements of the array,
olds the array size. To declare an array we use the
tions:
at elements.
int n[200]; // Array with 200 integer elements.
specific element in an array can be accessed using the bracket operator and supplying an array
index, which identifies the element:

0f to element zero.
Note: It does not take too much effort to realize that the functionality of the break and continue
statements can be implemented with if…else

T r, when variables wer

=std::string str
float f = 0.0f;
int n = 0;


H er, what if you need 1
declare so many variables an
f same type in a compo
contains n number of variables. We call the indi
nd we call the number of elements an array ha
following general syntax:



type identifier[n];

Where n is an integer constant that specifies the number of elements the array contains. Here are some
specific examples of array declara

float fArray[16]; // Array with 16 flo

std::string str[5000]; // Array with 5000 string elements.

A
fArray[0] = 1.0f; // Assign 1.

63
fArray[1] = 2.0f; // Assign 2.0f to element one.
fArray[12] = 13.0f;// Assign 13.0f to element twelve.
//fArray[20] = 21.0f;// !! BAD, OUT OF BOUNDS INDEX !!

Important:

Observe that arrays are zero-based; that is, the first element in the array is identified with an index of
zero. And therefore, the last element is identified with an index of
n-1
, where
n
is the total number of
elements.

Supplying an out of bounds index results in code that compiles—the compiler will not force you to correct

ou are essentially accessing memory that does not
fArray was declared to store 16 elements. Thus, an
t of bounds index.
cessed one by one and assigned an initial
t in
intArray[5] = 78;
intArray[6] = 0;
rray[7] = 4;

+ provides an alternative syntax:
Array[8] = {-4, 6, -2, 0, 33, 78, 0, 4};
entry in the curly brace list corresponds to element [0], the second entry to [1], and so on.
ent is explicitly initialized, the compiler can deduce
eds, and therefore, the array size, 8, is not explicitly required. That is,
is next statement is equivalent:
In actuality, all the preceding array initialization syntaxes are only practical for small arrays. Manually
initializing an array with a thousand elements, for example, is clearly impractical.
2.5.2 Iterating Over an Array
it. However, it is strongly advised not to do so as y
belong to you. In the former example, the array
index of 20 is an ou

2.5.1 Array Initialization
To initialize the elements of an array, each element could be ac
value like so:


in tArray[8];
intArray[0] = -4;
intArray[1] = 6;

intArray[2] = -2;
[3] = 0; intArray
intArray[4] = 33;


intA

In addition, C+


int int

Here the first
By using this curly brace notation, where each elem
how many elements the array ne
th


int intArray[] = {-4, 6, -2, 0, 33, 78, 0, 4};



64
Typically, when a large array of items are stored, the elements are somewhat related to a larger whole.
For example, in 3D computer graphics we usually represent a 3D object with an array of polygons.
hese polygons form a larger whole, namely the 3D object. If all of the polygon parts of the 3D object
3D object itself moves in that direction. As such, we normally do
ot modify the elements of arrays individually. Rather, we usually want to apply the same operation to
every element (e.g., initialize all elements to zero, add all corresponding elements of two arrays into a
third array). A loop is perfect for doing this. Program 2.16 iterates through every element in two arrays

of the same size and adds their corresponding elements together and stores the sum in a third array,
which is also of the same size.

Program 2.16: Program demonstrates iterating over arrays.
T
move in the same direction then the
n
#include <iostream>
using namespace std;

int main()
{
int array0[7] = {1, 2, 3, 4, 5, 6, 7};
int array1[7] = {-9, -8, -7, -6, -5, -4, -3};

int sum[7];//< Stores the addition result.
for(int i = 0; i < 7; ++i)
{
// Add the corresponding i-th elements and store in sum.
sum[i] = array0[i] + array1[i];

cout << array0[i] << " + " << array1[i] << " = ";
cout << sum[i] << endl;
}
}

Output 2.16.
1 + -9 = -8
2 + -8 = -6
3 + -7 = -4

4 + -6 = -2
5 + -5 = 0
6 + -4 = 2
7 + -3 = 4
Press any key to continue

Loops and arrays go hand-in-hand and many problems are solved using by them together. Note how the
ounter variable of the c for-loop naturally becomes an index into the i-th element of the array.
rrays

2 ltidimensional A.5.3 Mu

65
It is possible to have an array of arrays; that is, an array where each individual element is also an array.

One can be declared using the following double bracket syntax:


type identifier[m][n];

Figure 2.1: An array or arrays, where each element contains an array. If we say the array of arrays goes from top to
bottom and each element of this array of arrays contains an array going left to right then we have a table layout.

As Figure 2.1 shows, an array of arrays forms a rectangular table or matrix. The constant m specifies the
number of rows and the constant n specifies the number of columns. Such a matrix is of size (or
imension)
. Here are some specific examples of matrix declarations:
float fMatrix[16][12]; // Matrix with 16x12 elements.
int n[20][20]; // Matrix with 20x20 elements.
std::string str[500][100]; // Matrix with 500x100 elements.


We can access a specific element in a matrix using the double bracket syntax and supplying two array
dices, which identifies the row and column of the element:

fMatrix [0][0] = 1.0f; // Assign 1.0f.
= 2.0f; // Assign 2.0f.
] = 13.0f;// Assign 13.0f.
//fMatrix[16][3] = 21.0f;// !! BAD, OUT OF BOUNDS INDEX !!


In a
syntax
three columns.
{




};

d

nm ×



in

fMatrix [1][2]
fMatrix [12][10

ddition to performing individual element initializations, you can initialize matrices using curly brace
as shown here:


// Matrix with four rows of
int matrix[4][3] =

{1, 2, 3}, // Row 1
{4, 5, 6}, // Row 2
{7, 8, 9}, // Row 3
{10, 11, 12}// Row 4


66

Becaus ix is done with a double nested loop—one that
erates over the rows and one that iterates over the columns. The following double for-loop iterates
ove
for(int i = 0; i < 4; ++i)



New line for each row.
}


arrays and so on by following the same general pattern. That is, a 3D
s:

type identifier[m][n][p];

ultidimensional array greater than a 3D array to
avoid overly complex situations.

2.6 Summary
1. The relational operators allow us to determine certain elementary relationships between
a. The logical AND operator (
&&)
e of the extra dimension, iteration over a matr
it
r the preceding matrix and outputs its elements to the console window:

// Loop over rows.

{
// Loop over columns.
for(int j = 0; j < 3; ++j)
{
cout << matrix[i][j] << " ";
}
cout << endl; //
You can create arrays of arrays of
array would be declared a

But, as a rule of thumb, it is advised that you not use a m



variables, such as equality and inequality.

2. We use three logical operators:


b. The logical OR operator (
||)
operator (
!).
c. The logical NOT


67
These logical operators allow us to form more complex boolean expressions and therefore enable
make decisions at runtime. They allow us
ecuted if a particular condition is satisfied
ue then execute this code).
4. Loops enable us to repeat a block of code a variable number of times.

ontiguous block of memory that contains n amount of variables. We call the
les in an array the elements of the array, and we call the number of elements an
array holds, the array size.
2.7.1 Logical Operator Evaluation
hat Boolean value do the following expressions
|| B || C || D
&& B && C && D
d. !((A && B) || (B && !C)) || !(C && D)

e. !(!((A && !D) && (B || C)))

ne unit north, east, south or west.
ach time the player enters a selection, update the coordinates of the user and output the current
position. Start the player at the origin of the coordinate system. Your program’s output should look like
e followin :

ast, (S)outh, (W)est (Q)uit? n
urren P 0, 1)
Move (N)orth, (E)ast, (S)outh, (W)est (Q)uit? e
us to make more useful conditional statements.

to any program that needs to3. Conditionals are the key
to make certain that a block of code will only be ex
(i.e., if this condition is tr

5. An array is a c
individual variab

2.7 Exercises
Assume A is true, B is true, C is false and D is false. W
evaluate to?

a. A

b. A

c. !C && !D


2.7.2 Navigator
Write a program that displays a menu which allows the user to move o
E
th g

Current Position = (0, 0)
ove (N)orth, (E)M

C t osition = (

68
Curren osi
ove (N)orth, (E)ast, (S)outh, (W)est (Q)uit? s
w
ove (N)orth, (E)ast, (S)outh, (W)est (Q)uit? q
Write an averaging program. The program must prompt the user to enter a positive integer that specifies
es to average. The program must then ask the user to input these n
values. The program should then compute the average of the values inputted and output it to the user—
use the following average formula:
t P tion = (1, 1)
M
Current Position = (1, 0)
Move (N)orth, (E)ast, (S)outh, (W)est (Q)uit?
Current Position = (0, 0)
M
Exiting
Press any key to continue


2.7.3 Average
the number of values n the user wish

n
aaa
avg
n 110



+++
=
.

Your program’s output should look like the following:
1] = 2
2] = 3
3] = 4
[4] = 5
verage = 3
Factorial
orial of a positive integer n, denoted n!, is defined as follows:
)
ent, 0! = 1. To ensure that you are comfortable with the factorial operation, let us write out a
uple of examples.
• Evaluate 4!.

Enter the number of values to average: 5
0] = 1 [
[
[
[
A
Press any key to continue



2.7.4
The fact


()( )()()(
123 21 −−= nnn
.
n!

mBy agree
co


69
4! = 4

(3)(2)(1) = 24.
• Evaluate 6!.
trices. Consider




−++


631603001
63
Write a program that creates three matrix variables of dimension
6! = 6(5)(4)(3)(2)(1) = 720.

Write a program that asks the user to enter in a positive integer n. Compute the factorial of n and output
the result to the user. Your program’s output should look like the following:


Enter a positive integer to compute the factorial of: 5
5! = 120
Press any key to continue


2.7.5 Matrix Addition
The sum of two matrices is found by adding the corresponding elements of the two ma
the following two matrices and A B.




=A


=B


− 825


201


001


− 630

The sum, found by adding corresponding elements, is:




=+
BA





=




+++−
=




+



− 102428
0215201825





0001


32
×
, two of which are to be initialized
in such a way that they are identical to A and B; the third will be used to store the sum of A and B.
sing a double for-loop to iterate over the matrix elements, compute the sum of each component and
ore the result in the third matrix (e.g., C[i][j] = A[i][j] + B[i][j]). Finally, output the matrix sum. Your
program’s output should look like the following:
-5 2 8
1 0 0
=
y key to continue

U
st

A =

B
1 0 2
0 3 -6

A + B =
-4 2 10
1 3 -6

ress anP



70
2.7.6 ASCII
Write a program that outputs every character in the extended ASCII character set in the range [33, 255].
Note that we omit characters from [0, 32] since they are special command characters. (Hint: Recall that
characters are represented by the
char and unsigned char types, so simply loop through each
: 59: ; 60: < 61: = 62: >
D 69: E 70: F 71: G 72: H
97: a 98: b 99: c 100: d 101: e 102: f
03: g 104: h 105: i 106: j 107: k 108: l 109: m 110: n 111: o 112: p
: ụ 148: ử 149: ũ 150: ỷ 151: ự 152:
155: Â 156: Ê 157: Ơ 158: 159: 160: ỏ 161: ớ 162: ú
170: ơ 171: ẵ 172: ẳ
73: Ă 174: ô 175: ằ 176: 177: 178: 179: 180: 181: 182:
83: 184: 185: 186: 187: 188: 189: 190: 191: 192:
195: 196: 197: 198: 199: 200: 201: 202:
211: 212:


8: 239: 240: 241: 242:
252:
inear Search
t of data for values that have some
e and you want to
s; that is, a subset of
n order to do this, you will need to search the
rs of each class and copy those members into their corresponding class
subset.


possible value33-255and output it.) Your programs output should look like the following:

33: ! 34: " 35: # 36: $ 37: % 38: & 39: ' 40: ( 41: ) 42: *
43: + 44: , 45: - 46: . 47: / 48: 0 49: 1 50: 2 51: 3 52: 4
53: 5 54: 6 55: 7 56: 8 57: 9 58:
3: ? 64: @ 65: A 66: B 67: C 68:6
73: I 74: J 75: K 76: L 77: M 78: N 79: O 80: P 81: Q 82: R
83: S 84: T 85: U 86: V 87: W 88: X 89: Y 90: Z 91: [ 92: \
93: ] 94: ^ 95: _ 96: `
1
113: q 114: r 115: s 116: t 117: u 118: v 119: w 120: x 121: y 122: z
123: { 124: | 125: } 126: ~ 127: 128: ầ 129: ỹ 130: ộ 131: õ 132: ọ
133: 134: ồ 135: ỗ 136: ờ 137: ở 138: ố 139: ù 140: ợ 141: ỡ 142:
143: 144: ẫ 145: ổ 146: ặ 147
153: ệ 154: ĩ
163: ỳ 164: ủ 165: ẹ 166: ê 167: 168: 169:
1
1
193: 194:
203: 204: 205: 206: 207: 208: 209: 210:
213: 214: 215: 216:
217: 218: 219: 220: 221: 222:
223: 224: 225: ò 226: 227: 228: 229: 230: à 231: 232:
233: 234: 235: 236: 237: 23
43: 244: 245: 246: ữ 247: 248: 249: ã 250: ã 251: 2
253: 254: 255:
Press any key to continue




2.7.7 L
Background Information

In writing computer programs you will often need to search a se
particular properties. For example, imagine you have some fantasy role-playing gam
on the character classeorganize a global dataset of players into subsets based
a subset of clerics, and etc. Iwarriors, a subset of wizards,
global player list for the membe

71
As another example, suppose a
particular identification number,
business issues identification numbers to its customers. Given a
the business would like to search its customer database for the
customer information (e.g., name, address, order history, etc.) that corresponds with the given
that the value used for the search, which in this example is an identification
umber, is called a If the business searched for a customer’s information using the
xample
identification number. Note
search key.n
customer’s last name, then the last name would be the search key.

One method of searching a set of data is called a linear search. The linear search simply scans the
dataset element-by-element until it finds the elements it is looking for. Clearly, this search can be fast if
the particular element is found early on (not guaranteed), or can be slow if the particular element is one
of the last few elements to be scanned.

E : Find the array position of the value ‘9’ in the following dataset: {7, 3, 32, 2, 55, 34, 6, 13, 29,
22, 11, 9, 1, 5, 42, 39, 8}.


Solution: We use the linear search m
we find that the value ‘9’ is
ethod; that is, reading the array left to right and element-by-element
located in the eleventh position (e.g., index [11]) of the array (recall that
general, we have the following linear search algorithm:
ine S
array positions start at 0 and not 1).

In

L ar earch.
Let x[n] = x[0],…,x[n-1] be an array of given integers to search.
Let store the array index of the item we are searching for. Position be an integer to
Let are searching for. Value be the value we

For
0=i
to
1−n
, do the following:
If( x[i] = Value )
Position = i;
Break;
Else
Continue;

eExercis

rogram search the array for the integer the user entered and output its array position (i.e.,

s array index). Your output should look similar to the following:
tem f dex [4]
Press any key to continue


Hardcode the following integer array: {7, 3, 32, 2, 55, 34, 6, 13, 29, 22, 11, 9, 1, 5, 42, 39, 8} into your
rogram. Display this array to the user. Then ask the user to input an integer to search for. Yourp
p should then
it

List = 7, 3, 32, 2, 55, 34, 6, 13, 29, 22, 11, 9, 1, 5, 42, 39, 8
nter an integer in the list to search for: 55 E
I ound at in

72
2.7.8 Selection Sort
Background Information
you may want to sort records
f customers by age, zip code, and/or gender; or in 3D computer graphics you might want to sort 3D
geometry (e.g., polygons) based on their distance from the viewer. Because sorting is so important, we
ill end up spending several lab projects working on the different sorting techniques that have been
also

A frequent task that occurs in writing computer programs is the need to sort a set of data. For example,
you might want a list of integers sorted in ascending or descending order;
o
w
devised. However, to begin with, we will start with one of the simplest (and one of the least
efficient) sorting methods, called the selection sort.


The selection sort algorithm is as follows:

Ascending order Selection Sort.
Let x[n] = x[0], ,x[n-1] be an array of given integers to sort.
Let p be an integer to store an array index.

For
0=i
to
2−n
, do the following:

1. Find the array index of the smallest value in the subarray x[i],…,x[n-1] and store
it in p.
2. Swap x[i] and x[p].
3. Increment i.

To be sure that you understand what this algorithm specifies, consider the following example:

Example:

Consider the following integer array:
= { 7, 4, 1, 8, 3 };
we scan through the subarray x[0],…,x[n-1] and search for the smallest number. We find
t integer 1 is located at index p = 2. The algorithm then tells us to swap x[i] and x[p],
tly means to swap x[0] and x[2]. Doing so yields the new array configuration:
barray x[1],…,x[n-1] and searching for the
= 4. Swapping x[1] and x[4] yields:
1, 3, 7, 8, 4



x[5]
When
0=i
allesthat the sm
which curren

1, 4, 7, 8, 3

1
. Scanning through the su
Incrementing i, we now have
=i
smallest integer we find 3 at index p


73
Incrementing i, we now have
2=i
. Scanning through
smallest integer we find 4 at index p = 4. Swapping x[2

1, 3, 4, 8, 7
the subarray x[2],…,x[n-1] and searching for the
] and x[4] yields:

Incrementing i, we now have
. Scanning through the subarray x[3],…,x[n-1] and searching for the
smallest integer we find 7 at index p = 4. Swapping x[3] and x[4] yields:


1, 3, 4, 7, 8
. Observe that we make
passes, since the
ts.
As you can see, this algorithm moves one element into its correct sorted position per pass. That is, for
each cycle it finds the smallest element in the subarray x[i],…,x[n-1] and moves it to its correct sorted
osition, which is the front of the subarray: x[i]. This makes sense because, if we are sorting in
cending order then the smallest element in the subarray x[i],…,x[n-1] should be first. Because each
pass correctly sorts one element, we do not need to consider that element anymore. We effectively
nore that element by shortening the subarray by one element (incrementing i). We then repeat the
ocess with our new shortened subarray by searching for the next smallest element and placing it in its
sorted position, and so on, until we have sorted the entire array.
xercise
3=i

We have successfully sorted the array in ascending order
last pass correctly sorts both the x[n-2] and x[n-1] elemen

2−n
p
as
ig
pr

E

sk the user to input ten random (non-sorted) integers and store them in an array. Sort these integers in
cending order using the selection sort and output the sorted array to the user. Your output should
look similar to the following:


ter ten unsorted integers
] = 5
[1] = -3
[2] = 2
] = 1
] = 7
[5] = -9
[6] = 4
] = -5
] = 6
[9] = -12

sorted List = 5, -3, 2, 1, 7, -9, 4, -5, 6, -12,
rting
Sorted List = -12, -9, -5, -3, 1, 2, 4, 5, 6, 7,
Press any key to continue

A
as
En
[0
[3
[4
[7
[8
Un
So




74

×