Text-only version

This is Google's cache of http://cgamedev.blogspot.com/p/codelab-answers.html. It is a snapshot of the page as it appeared on Feb 5, 2012 18:40:12 GMT. The
current page could have changed in the meantime. Learn more




CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
1 of 20 2/9/2012 7:19 AM




CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
2 of 20 2/9/2012 7:19 AM
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
3 of 20 2/9/2012 7:19 AM
o Declare a variable x , suitable for storing values like 3.14159 and 6.02E23.
• float. x;
• 10510
o Declare an integer variable cardslnHand and to 13.
• int cardslnHand = 13;
• 10511
o Declare a vanable temperature and it to 98.6.
• float temperature • 98 . 6;
• 10512
o Declare a numerical variable precise and initialize it to the value
1.09388641.
• double precise 1.09388641;
• 10943
o Write a statement that declares and initializes two integer variables. Call
the first one age and initialize it to 15, and call the second one weight and
initialize it to 90.
• inl age 15;
inl weight 90;
• 10962
o Declare a floating point variable named distance.
• float distance;
• 10983
o Write a statement that declares a double variable named dosage.
• double dosage;
• 10931
o Wnte a declaration of a variable named count that can be used to hold
numbers hke 9 and -1 and -4.
• int count;
• 10933
o Write a declaration of a variable named number_of_children that can be
used to hold the number of children in a family.
• int number of_children;
• 10934
o Write a declaration for a variable hits that can hold the number of times a
baseball player has hit the ball in a baseball game.
• int. hiLs ;
• 10902
o Write a declaration of a variable named numberOfWidgets that can be
used to hold numbers like 57 and 981 and -4.
• inl numberOfWidgets;
• 10903
o Write a statement that declares an int variable presidentaiTerm and
initializes it to 4.
• int presidentalTerm 4;
• 10904
o Wnte a declaratiOn of an int variable year and 365.
• int year 365;
• 10938
o Write a declaration for an integer variable area and a variable price that
can hold numbers with decimal places.
• 10939
• int area;
double price;
o Write a declaration for variables length, width, and area that can hold
values like 13.5 and 14.6.
• double length, width, area;
• 10940
o Write a declaration for a variable channel that can hold TV channel
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
4 of 20 2/9/2012 7:19 AM
numbers (1-900) and a variable hours_recorded that can hold the number
of hours of TV recorded (numbers like 1.0 or 3.5).
• int channel ;
double hours_recorded;
• 10932
o Write a declaration for a variable rate_of_pay lhat can hold values like
11.50 or 12.75.
• double rate_of_pay;
• 10935
o Write a declaration for a variable temperature that can hold the current
outdoor temperature, measures to the half degree (like 98.6 or 31.5).
• double temperature;
• 10937
o Write a declaration for two variables, price and cost, that can hold numbers
with decimal places.
• double price, cost;
• 10941
o Write a statement that declares an int variable age and initializes it to 15.
• inl age 15;
• 10942
o Write a statement that declares two int variables, named num and val and
initializes each to 5.
• int num ... 5, val 5;
• 10944
o Declare a variable m11es_run and initialize it to 3. 75.
• !loat miles run • 3 . 75 ;
• 10946
o Write statements to declare and initialize two variables: one, named
element_ number can hold any integer values 1 through 118; lhe olher,
names atomic_ weight can hold atomic weight of the given element; atomic
weights are values l1ke 3. 76.
In the declaration, initialize lhe variable to the values for oxygen, which is
element number 8 and has an atomic weight of 15.9994.
• int element number • 8;
double atomic_weight = 15 . 9994;
• 10945
o Write a declaration statements to declare and initialize two variables: one
is an integer variable names age, initialized to 18, and the other variable,
named weight, is initialized to 114.5.
• inl age 18;
double weight 114 . 5 ;
• 60110
o Question 1: Which is the best identifier for a variable to represent the
amount of money your boss pays you each month?
• monthlyPay
• 60118
o Question 1: An identifier that cannot be used as a variable name is a
____ word.
• reserved
• 60106
o Question 1: Which of the following is NOT a legal identifier?
• 7thheaven
• 60108
o Which of the following IS a legal identifier?
• 85016
o Question 1: Of the following variable names, which is the best one for
keeping track of whether a patient has a fever or not?
• hasFever
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
5 of 20 2/9/2012 7:19 AM
o Question 2: Of the following variable names, which is the best one for
keeping track of whether an integer might be prime or not?
Express1ons
• 10526
• mightBePrime
o Wnte an expression that computes the sum of two variables verbal Score
and math Score (already declared and assigned values).
• verbalScore + mathScore
• 10527
o Given the variables taxablePurchases and taxFreePurchases (already
declared and assigned values). w r ~ e an expression corresponding to the
Iota I amount purchased.
• taxablePurchases + taxFreePurchases
• 10528
o Write and expression that computes the difference of the variables
endlngTime and startingTime.
• endingTime - startingTi me
• 10529
o Given the variables fuiiAdmissionPrice and di scountAmount (already
declared and assigned values). write an expression corresponding to the
price of a discount admission. (The variable di scountAmount holds the
actual amount discounted, not a percentage.)
• fullAdmissionPrice - discountAmount
• 10530
o GIVen the vanable pricePerCase , write an expression corresponding to
the pric of a dozen cases.
• pricePerCase • 12
• 10531
o Given the variables costOfBusRental and maxBusRiders , write an
expression corresponding to the cost per rider (assuming the bus is full).
• costOfBusRental I maxBusRiders
• 10532
o Write an expression that computes the remainder of the variable principal
when divided by the variable divisor. (Assume both are type int).
• pt inclpal \ divjsor
• 10533
o Write an expression that computes the average of the values 12 and 40.
• 140 + 12) I 2
• 10534
o Write and expression that computes the average of the variables exam1
and exam2 (both declared and assigned values).
• (examl • exam2) I 2
• 10905
o Assume that an i nt variable x that has already been declared. Write an
expression whose value is 1 more than x.
• x + I or I + x
• 11014
o A wall has been built with two pieces of sheetrock, a smaller one and a
larger one. The length of the smaller one is stored in the variable small.
Similar1y, the length of the larger one is stored in the variable large. Write
a single expression whose value is the length of this wall.
• large + small
• 11100
o Assume that an lnt variable x that has already been declared. Write and
expression whose val ue is the last (rightmost) digit of x.
o X \ 10
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
6 of 20 2/9/2012 7:19 AM
• 11001
o Assume that price is an integer variable whose value is the price (in US
currency) in cents of an item. Assuming the item is paid for with a
minimum amount of change and just single dollars, write an expression for
the number of single dollars that would have to be paid.
• price I !00
• 11022
o Assume that price IS an Integer vanable whose value is the price (in US
currency) in cents of an item. Assuming the nem is paid for with a
mm1mum amount of change and just single dollars, write an expressiOn for
the amount of change (in cents) that would have to be paid.
• price \ 100
• 11015
o Each of the walls of a room with square dimensions has been built with two
p1eces of sheetrock, a smaller one and a larger one. The length of the
small ones is the same and is stored in the variable small. Similarly, the
length of the larger ones is the same and is stored in the variable large.
Write a single expression whose value is the total area of this room. 00
NOT use the pow function.
• + small ) • (large + small )
• 11013
o The dimensions (width and length) of room1 have been read into two
variables: width1 and length1 . The dimensions of room2 have been read
into two other variables: width2 and length2 . wrne a single expression
whose value is the total area of the two rooms.
• length! • widthl + length2 • width2
• 10608
o Given two mteger variables distance and speed , write an expression that
divides distance by speed using floating point arithmetic, i .e a fractional
resuH should be produced.
• (double)distance/speed
• 60065
o Question 1: Which of the following is NOT an operator?
• add
o Question 2: Which of the following is NOT an operator?
• 60066
o Question 1: Which of the following is NOT an expression?
• Pl =3. 14159
o Question 2: Which of the following is NOT an expression?
• int prime . 37
Ass1gnments
• 10538
o Given an integer variable dri vingAge that has already been declared,
write a statement that assigns the value 17 to drivingAge.
• drivingAge = 17;
• 10947
o Wnte a statement to set the value of num to 4 (num is a variable that has
already been declared).
• num 4 ;
• 10539
o Given two Integer vanables oldRecord and newRecord , a
statement that gives newRecord the same value that old Record has.
• newRecord - oldRecord;
• 10540
o Given two Integer variables matricAge and gradAge , write a statement
that gives gradAge a value that is 4 more than the value of matrlcAge.
• g1adAge + 4;
• 10955
o Wri te a statement to assign to weight_in_pounds the value of
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
7 of 20 2/9/2012 7:19 AM
weight_in_kilos times 2.2. (The variables have already been declared and
weight_in_kilos has already been initialiZed).
• weiqht_in_pounds • weiqht_in_kilos • 2 . 2;
• 10949
o Write a statement to set the value of ans equal to the value of num plus 5.
(These variables have already been declared and num has already been
initialized).
• ans nwn • 5 ;
• 10957
o Write a statement to find the remainder rem when num is divided by S.
(The vanables have already been declared and num has already been
initialized).
• rem • num \ 5 ;
• 10952
o Write a statement to subract tax from gross_pay and assign the result to
net_pay . (The variables have already been declared and gross_pay and
tax have already been initialized).
• net pay • qross_pay - tax;
• 10956
o Write a statement to assign to kilos the value of pounds divided by 2.2.
(The variables have already been declared and pounds has already been
initialized).
• kilos pounds I 2 . 2;
• 10950
o Write a statement to set the value of price equal to three time the value of
cost. 9The variables have already been declared and cost has already
been inrtialiZed).
• price 3 • cost ;
• 10953
o Write a statement to set the value of area to the value of length times the
value of Width. (The variables have already been declared and length and
width have already been initialized).
• area • length • width;
• 10954
o Write a statement to multiple diameter by 3.14159 and assign the result to
circumference, (The variables have already been declared and diameter
has already been initialized).
• circumference diameter • 3 . 14159;
• 10951
o Write a statement to add the values of x andy together, storing the result
in sum. (The variables have already been declared and x and y have
already been initialized).
• sum X + y;
• 10542
o Given the integer variable profits , write a statement that increases the
value of that variable by a factor of 10.
• profits • - 10;
• 10960
o Wnte a statement using a compound assignment operator to add 5 to val
(can 1nteger vanable that has already been declared and initialized).
• val • 5;
• 10962
o Write a statement using a compound assignment operator to cut the value
of pay 1n half (pay is an integer variable that has already been declared
and initialized).
• pay I 2;
• 10963
o Write a statement using a compound assignment operator to multiple
num_rabbits by 4, changing the value of num_rabbits (num_rabbi ts has
already been declared and initialized).
• num rabbits *= ~ ;

CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
8 of 20 2/9/2012 7:19 AM
• 10964
o Write a statement using a compound assignment operator to change val to
the remainder when val is divided by 16 (val has already been declared
and initialized).
• val \= 16;
• 10543
o Given an integer variable strawsOnCamel , write a statement that uses
the auto-increment operator to increase the value of that vari able by 1.
• strawsOnCamel++;
• 10544
o Given an integer variable timer , write a statement that uses the
auto-decrement operator to decrease the value of that variable by 1.
• timer--;
• 10548
o Given two int variables, i and j . which have been declared and initialized,
and two other i nt variables, itemp and jtemp , which have been declared,
write some code that swaps the values in i and j by copying their values to
itemp and jtemp , respectively, and then copying itemp and j temp to j
and i , respectively.
• 10549
• itemp = i ;
jtemp • j ;
jtemp;
j • itemp;
o Given three already declared i nt variables, i , j , and temp , write some
code that swaps the values in i and j . Use temp to hold the value of i and
then assign j 's value to i. The original value of i , which was saved in
temp , can now be assigned to j .
• 10550
• temp • i ;
i j ;
• temp;
o Given two int variables, f irstPiaceWi nner and secondPiaceWinner .
write some code that swaps their values. Declare any additional variables
as necessary, but do not redeclare firstPiaceWinner and
secondPiaceWinner.
• 10958
• int temp;
temp = firstPlaceWinner ;
firstPlaceWinner • secondPlaceWinner;
secondPlaceWinner = temp;
o Write a statement using the increment operator to increase the value of
num_items (an already declared integer variable) by 1.
• num_items++;
• 10959
o Write a stat ement using the decrement operator to decrease the value of
count (an already declared integer variable) by 1.
• count --;
• 60128
o Question 1: Consider this code: "int v = 20; -v; cout « v++;" . What value
is printed, what value is v left with?
• 19 is printed, vends up with 20
o Question 2: Consider this code: "int s = 20; int t = s++ + -s;" . What are the
values of s and t?
• s is 20 and t cannot be determined
Constants
• 10520
o Declare an i nt constant Monthsl nDecade whose value is the value of the
constant Monthsl nYear (already declared) multiplied by 10.
• const int MonthslnDecade • MonthslnYear * 10;
Console 1-0
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
9 of 20 2/9/2012 7:19 AM
• 10505
o Given an integer variable count, write a statement that writes the value of
count to standard output (When we say "given· , that means that count has
ALREADY been declared - so you should not declare it!)
Do not wnte anything else to standard output- just the value of count. In
particular, your output should NOT include something like "count=". The
output should be JUST the value of the variable count.
• count << count ;
• 10506
o Given a floating-point variable fracti on , write a statement that w r ~ e s the
value of fraction to standard output. Do not write anything else to
standard output-- just the value of fraction.
• cout << fraction;
• 10507
o The exercise instructions here are LONG - please read them all carefully.
If you see an internal scroll bar to the right of these instructions, be sure to
scroll down to read everything.
Given an integer variable i and a floating-point variable f, wri te a statement
that writes both of their values to standard output in the following format:
i = value-of-i f = value-of-f
Thus, if i's value were 25 and fs value were 12.34, the output would be: i =
25 f = 12.34
But you don1 know what i's value and fs value are. They might be 187
and 25.06. If that's What their val ue are, the output from your statement
should be: i = 187 f = 24.06
Remember: You are GIVEN i and f --that means they are already
declared and they already have values! Don't change their values by
aSSIQmng or initialiZing them! Just print them out the way we have shown
above. Just write one statement to produce the output.
Remember: In your output you must be displaying both the name of the
variable (like i) and its value.
• cout << "i " << i << "f•" << f ;
• 10966
o Write a single statement that will print the message "first is • followed by
the value of first, and then a space, followed by "second = •. followed by
the value of second. Print everything on one l ine and go to a new tine after
printing. Assume that first has already been declared as a double and that
second has been declared as an int. Assume also that the variables have
already been given values.
• 60103
• cout << '' first is '' << fi rst <<" second • '' <<
second << endl ;
o Question 1: How many spaces printed out by this statement: cout « "how"
<< "now"<< "brown"<< "cow" << "?";
• 0
o Question 2: How many spaces printed out by this statement: cout «
"abc\ndel\tghi\njkr « endl « endl « "mno\n\npqr\n";
• 6
• 11023
o Assume that price is an integer variable whose value is the price (in US
currency) in cents of an item. Write a statement that prints the value of
price in the form ·x dollars and Y cents". So, if the value of price was
4321 , your code would print "43 dollars and 21 cents". If the value was
501 it would print "5 dollars and 1 cents". If the value was 99 your code
would print ·o dollars and 99 cents".
• 10968
• cout << price/100 << "dollars and " <<
price\100 << " cents";
o Write a statement that reads a fl oating point (real) value from standard
input into temperature. Assume that temperature has already been
declared as a double variable.
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
10 of 20 2/9/2012 7:19 AM
• cin >> temperature;
• 10967
o Write a statement that reads an integer value from standard input into val.
Assume that val has already been declared as an int variable.
• cin >> val ;
• 10978
o Write an expression that attempts to read an integer from standard input
and store it in an int variable, x, that has already been declared.
• cin >> x ;
• 11006
o Write a statement that reads a word from standard input into firstWord.
Assume hat firstWord has already been declared as a char array large
enough to hold a 50-letter-word.
• cin >> firstWord;
• 11011
o Assume that name has been declared suitably for storing names (like
"Amy" , "Fritz" and "Moustafa"). Write some code that reads a value into
name then prints the message "Greetings,NAME!!!" where NAME is
replaced the value that was read into name.
For example, if your code read in "Hassan" it would print out "Greetings,
Hassaon!!l".
• cin >> name;
cout <<
11
Greetings ," << name << n! ! ! ";
• 11009
o Assume that name and age have been declared suitably for storing names
(like "Abdullah" , "Alexandra" and "Zoe") and ages respectively. Write
some code that reads in a name and an age and then prints the message
''The age of NAME is AGE." where NAME and AGE are replaced by the
values read in for the variables name and age.
For example, if your code read in "Rphit" and 70 then it would print out
"The age of Rohit is 70."
• cin >> name >> age;
cout << '"rhe age of " << name << " is " << age
(( II n •
• 11010
o Assume that name has been declared suitably for storing names (like
"Misha" , "Emily" and "Sofia"). Write some code that reads a value into
name then prints the message "Greeting, NAME" where NAME is replaced
the value that was read into name.
For example, if your code read in "Rachel" it would print out
"Greeting,Rachel".
• cin >> name;
cout << "Greetings ," << name;
• 10515
o Write a complete program that
- Declares an integer variable
Comments
- Reads a val ue from the keyboard into the variable
-Writes to standard output the variable's value, twice the value, and the
square of the value, separated by spaces.
Besides the numbers, nothing else should be written to standard output
except for spaces separating the values.
• finclude <iostream>
using namespace std;
i nt main()
int k;
cin >> k;
cout << k << " " << k "' 2 << " " << k "- k;


CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
11 of 20 2/9/2012 7:19 AM

CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
12 of 20 2/9/2012 7:19 AM
!ever false;
Multrway 1f else
• 10568
o Wnte an if/else statement that compares the double variable pH with 7.0
and makes the followmg assignments to the boot variables neutral , base
, and acid .
false, false, true 1f pH is less than 7
false, true, false If pH ts greater than 7
true, false, false if pH is equal to 7
• 11063
• if (pH < 7) I
neutral = false;
base • false;
acid - true;
if (pH > 7 )
neutral false;
b«se true;
actd • false;
if ( pH •• 7 ) I
neutral • true;
base false;
acid • false;
o Write a statement that compares the values of score1 and score2 and
takes the following acbons. When score1 exceeds score2 • the message
"player1 wins" is printed to standard out. When score2 exceeds score1 •
the message "player2 wins· is printed to standard out. In each case, the
vanables player1Wins , player1Losses , player2Wins , player2Losses ,
are Incremented when appropriate.
F1nally, in the event of a be, the message "tie" is printed and the variable
tieCount IS incremented.
• 11071
• if (scorel > score2) I
cout << "playerl wins";
playerlWins++;
player2Lossess++;
i! (score2 > scorel) (
e l se
coul << "player2 wins ";
player2Wins++;
playerlLosses++;
coul << "tie";
LieCount++;
o Clunker Motors Inc. is recalling all vehicles in its Extravagant tine from
model years 1999-2002 as well all vehicles in ~ s Guzzler line from model
years 2004-2007. Given a variable modeiYear and a string model Name
wnte a statement that pnnts the message "RECALL· to standard output 1f
the values of modeiYear and model Name match the recall detatls.
• 11072
• if (modelName
modelYear &&
"Extravagant " && 1999 <•
modelYear <• 2002 II modelName "Guzzler"
"
2004 <• modelYear && modelYear <= 2007)
cout << " RECALL" << endl ;
o Clunker Motors Inc. IS recalling all vehicles in its Extravagant line from
model years 1999-2002 as well all vehicles in its Guzzler line from model
years 2004-2007. A bool variable named recalled has been declared.
Given a variable modeiYear and a string modeiName write a statement
that assign true to recalled if the values of modeiYear and model Name
match the recall details and assigns false otherwise.
Do not use an if statement in this exercise!
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
13 of 20 2/9/2012 7:19 AM
• 11079
• recalled - (modelName == " Extravagant " H 1999
<•
modelYear && modelYear <• 2002 I I model Name
" Gizzler" && 2004 <• modelYear && modelYear
<- 2001) ;
o Assume that an int variable age has been declared and already given a
value. Assume further that the user has just been presented With the
folloWing menu:
S: hanger steak, red potatoes, asparagus
T: whole trout, long rice, brussel sprouts
8: cheddar cheeseburger, steak fries, cole slaw
(Yes, this menu really IS a menu!)
Write some code that reads the character (S or T or B) that the user types
in into a char variable choice that has already been declared and prints
out a recommended accompanying drink as follows: if the value of age is
21 or lower, the recommendation is "vegetable juice" for steak, "cranberry
juice" for trout, and "soda" for the burger. Otherwise, the
recommendations are "cabernet", "chardonnay", and "IPA" for steak, trout,
and burger respectively. Regardless of the value of age , your code should
print "invalid menu selection" if the character read into choice was not S or
TorS.
• 11064
• cin >> choice;
if (age <• 21)
if (choice== ' S ' )
cout << "vegetable juice";
else if (choice== ' T ' )
cout << "cranberry juice";
else if (choice •• ' 8 ' )
cout << "soda";
else
cout << "invalid menu selection";
else
if (choice •• ' S ' )
cout << "cabernet ";
else if (choice== ' T ' )
cout << nchardonnay";
else if (choice •• ' 8 ' )
cout << "IPA'' ;
else
cout << '' invalid me nu selection";
o Online Book Merchants offers premium customers 1 free book with every
purchase of 5 or more books and offers 2 free books with every purchase
of 8 or more books. It offers regular customers 1 free book with every
purchase of 7 or more books, and offers 2 free books with every purchase
of 12 or more books.
Write a statement that assigns freeBooks the appropriate value based on
the values of the bool variable isPremiumCustomer and the int variable
nbooksPurchased .
• if (isPremiumCustomer)
if (nbooksPurchased >• 8)
freeBooks = 2;
else if (nbooksPurchased >= 5)
freeBooks 1;
else
free8ooks • 0;
else
if (nbooksPurchased >= 12)
freeBooks = 2;
else if (nbooksPurchased >= 1)
free Books • 1;
else
freeBooks • 0;

CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
14 of 20 2/9/2012 7:19 AM
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
15 of 20 2/9/2012 7:19 AM
o In the Happy Valley School System, children are classified by age as
follows:
less than 2, ineligible
2, toddler
3-5, early childhood
6-7, young reader
8-10, elementary
11 and 12, middle
13, ImposSible
14-16, high school
• switch (age)
case 2 :
cout << " toddler";
break;
case 3 :
case 4 :
case 5 :
cout << "early childhood";
break;
case 6 :
case 7 :
cout << "young reader";
break;
case 8 :
case 9:
case 10 :
cout << '' elementary";
break;
case 11 :
case 12 :
cout << "middle";
break;
case 13 :
cout <<
break;
• 11074
case 14 :
case 15:
case 16:
cout << "high school";
break;
case 17 :
case 18 :
cout << '' scholar'';
brea k;
default :
cout << '' ineligibl e ";
break;
o HTTP is the protocol that governs communications between web servers
and web clients (i .e. browsers). Part of the protocol includes a status code
returned by the server to tell the browser the status of its most recent page
request. Some of the codes and their meanings are listed below:
200, OK (fulfilled)
403, forbidden
404, not found
500, server error
Given an 1nt variable status , wrne a swnch statement that prints out the
appropnate labet from the above list based on status .
• switch (status) (
case 200 :
cout << "OK (fulfilled) ";
break;
case 403 :
cout << n forbidden tl;
break;
case 404:
cout << "not found";
break;
case 500 :
cout << '' server error";


CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
16 of 20 2/9/2012 7:19 AM
break;
Classes, Strings, and fstreams
• 11054
o Read first a user's given name followed by the user's age from standard
input. Then use an ofstream object named outdata to write this
information separated by a space into a file called outdata . Assume that
this is the extent of the output that this program will do.
• 11045
• string name;
int age;
cin >> name;
cin >> age;
outdata . open ( "outdata", ios : : out) :
outdata << name << " " << age << endl ;
outdata . close( l;
o Given an i fstream object named input1 , associate it with a fi le named
wlnterdata.txt by opening the file for reading.
• inpull . open {"winterdata . t x t ") ;
• 11126
o Given the availability of a fi le named numbers write the statements
necessary to read an integer from standard input and then read in that
many values from numbers and display their total.
• 10844
• ifstream infile;
in file . open ( "numbers" ) ;
int total 0;
int n, x;
cin >> n;
for (int i -0; i<n; i++)
infile >> x ;
total + x ;
cout << total << endl ;
o Declare a string variable named oneS pace , and initialize it to a string
consisting of a single space.
• string oneSpace • '' '' ·
• 10720
o Write an expression that whose value is the fi fth character of the string
names.
• name [ 4 I
• 11171
o Write a full class definition for a class named Player , and containing the
following members:
- A data member name of type string .
- A data member score of type i nt .
- A member function called setName that accepts a parameter and
assigns 1t to name .
The function returns no value
- A member function called setScore that accepts a parameter and
assigns it to score .
The funcbon returns no value.
- A member function called getName that accepts no parameters and
returns the value of
name .
- A member function called getScore that accepts no parameters and
returns the value of
score .
• class Player {
private :
string name ;
int score ;
public:


CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
17 of 20 2/9/2012 7:19 AM
• 11174
) ;
void setName (string) ;
void setScore(int) ;
string getName () ;
int getScore () ;
void Player : : setName (string n)
name • n;
void Player : : setScore(int s)
score = s ;
string Player : : getName ()
(
return name ;
o Write a fu!l class definition for a class named Counter • and containing the
fo!lowing members:
-A data member counter of type int .
-A construclor that takes one int argument and assigns its value t o
counter
-A function ca!led increment that accepts no parameters and returns no
value.
Increment adds one to the counter data member.
-A function ca!led decrement that accepts no parameters and returns no
value.
Decrement subtracts one to the counter data member.
-A function ca!led getValue that accepts no parameters. It returns the
value of the
• 11182
instance variable counter .
• class Counter (
private :
) ;
i nt counter;
public:
Counter(int) ;
void increment () ;
void decrement () ;
int getValue () ;
Counter : : Counter (int i ) : counter(i) {}
void Counter : : increment( )
counter++;
void Counter : :decrement( )
counter--;
o Write a fu(l class definition for a class named Averager , and containing
the fo!lowing members:
-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 get Sum 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



CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
18 of 20 2/9/2012 7:19 AM
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).
• class Averager (
private :
int sum, count;
public:
Ave r ager () ;
in l getSum () ;
void add (int);
int getcount () ;
double getAverage ( );
);
Averager :: Averager () sum( O), count (O) ( )
int Averager :: getSum( )
return sum;
void Averager :: add(int val)
sum -+• val ;
count .. + ;
inl Averager : : getCount()
return count ;
double Averager:: getAver age ()
return (( doubl e ) s um) I count ;
Other Codelab answers that I have
• 10581
o Given an i nt variable n that has al ready been declared and initialized to a
posttive value, and another int variable j that has already been declared,
use a do ... while loop to print a single line consisting of n asterisks. Thus if
n contatns 5, five astensks will be printed. Use no variables other than n
and j .
• do
c o ut << "•"·
n--;
while (n > 0) ;
• 11127
o Given an tnt variable n that has already been declared, write some code
that repeatedly reads a value into n until at last a number between 1 and
10 (tnclusive) has been entered.
• 10585
• while (n < 1 I I n > 10) (
cin >> n;
o Assume the lnt variables I , to , hi , and result have been declared and
that to and hi have been ini tialized.
CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
19 of 20 2/9/2012 7:19 AM
Write a for loop that adds the integers between lo and hi (inclusive), and
stores the result i n result .
Your code should bot change the values of lo and hi . Also, do not declare
any additional variables- use only i , lo , hi , and result .
• for (i • lo; i <= hi ; i++)
result +- i ;
• 10639
o prlntTodaysOate IS a function that accepts no parameters and returns no
value. Wnte a statement that calls printTodaysOate .
• printTodaysOate( ) ;
• 10640
o prlntErrorOescription is a function that accepts one int parameter and
returns no value. Write a statement that calls the function
prlntErrorOescription , passing it the value 14.
• pri ntEr r orOescrip tion( l 4);
• 10642
o add is a function that accepts two int parameters and returns their sum.
Two lnt variables, euroSales and asiaSales , have already been declared
an initialized. Another int variable, eurasiaSales , has already been
declared.
Write a statement that calls add to compute the sum of euroSales and
aslaSales and store this value in eurasiaSales .
• eurasiaSales = add ( euroSales , asiaSales) ;
• 10648
o Wnte a statement that declares a prototype for a function printlarger ,
which has two int parameters and returns no value.
• void printLarger( int a, int b ) ;
• 10656
o Write the definition of a function pri ntAttitude , which has an int
parameter and returns nothing. The function prints a message to standard
output depending on the value of its parameter.
If the parameter equals 1, the function prints di sagree!! the parameter
equals 2, the function prints no opinionlf the parameter equals 3, the
function prints agree In the case of other values, the function does nothing.
Each message is printed on a line by itself.
• void printAtti t ude (int x) {
if ( X 1)
• 10655
cout << "disagree" << endl ;
if (x••2 )
cout << "no opinion" << e ndl ;
if (x••3 )
cout << "agree" << endl ;
o Write the definition of a function printGrade , which has a char parameter
and returns nothing. The function prints on a line by itself the message
string Grade: followed by the char parameter (printed as a character) to
standard output. Don't forget to put a new line character at the end of your
li ne.
Thus, i f the value of the parameter is 'A', the function print out Grade: A
• void printGrade (char x) {
cout << " Grade : " << x << endl ;
MORE COMING SOON!

CgameDev: CodeLab Answers http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...
20 of 20 2/9/2012 7:19 AM
Recommend this on Go ogle
Home
Subscri be to: Posts (Atom)
Public Slog. Simple template. Powered by Blogger.

CgameDev: CodeLab Answers

http://webcache.googleusercontent.com/search?q=cache:yuFlRoSgTaMJ...

2 of 20

2/9/2012 7:19 AM

• 10938 o Write a declaration for an integer variable area and a variable price that can hold numbers with decimal places.6. x . • int cardslnHand = 13 . • 10902 o Write a declaration of a variable named numberOfWidgets that can be used to hold numbers like 57 and 981 and -4. 15.. • int number of_children . • 10903 o Write a statement that declares an int variable presidentaiTerm and initializes it to 4. • int. • inl numberOfWidgets.09388641 . • inl age 90 . • float.5 and 14. • double precise 1. • float distance . • 10940 o Write a declaration for a variable channel that can hold TV channel 3 of 20 2/9/2012 7:19 AM .09388641 .6.. • 10511 o Declare a vanable temperature and in~ialize it to 98.com/search?q=cache:yuFlRoSgTaMJ. and call the second one weight and initialize it to 90. o Declare a variable x . • 10510 o Declare an integer variable cardslnHand and initialize~ to 13. area . • 10939 o Write a declaration for variables length. 6. • float temperature • 98 . • 10983 o Write a statement that declares a double variable named dosage. • 10931 o Wnte a declaration of a variable named count that can be used to hold numbers hke 9 and -1 and -4. • 10933 o Write a declaration of a variable named number_of_children that can be used to hold the number of children in a family. • 10934 o Write a declaration for a variable hits that can hold the number of times a baseball player has hit the ball in a baseball game. and area that can hold values like 13. hiLs .CgameDev: CodeLab Answers http://webcache.googleusercontent. w idth. • 10512 o Declare a numerical variable precise and initialize it to the value 1. double price . • double dosage. • 10904 o Wnte a declaratiOn of an int variable year and • int year 365 . suitable for storing values like 3. width .14159 and 6. • 10943 o Write a statement that declares and initializes two integer variables. inl weight • 10962 o Declare a floating point variable named distance.02E23. • int area . in~ialize ~to 365. • int presidentalTerm 4. Call the first one age and initialize it to 15. • double length. • int count .

that can hold numbers with decimal places.76.CgameDev: CodeLab Answers http://webcache. • double price . • int element number • 8 .com/search?q=cache:yuFlRoSgTaMJ. • !loat miles run • 3 . • double temperature . names atomic_weight can hold atomic weight of the given element. • inl age • 10942 15..75.. o Declare a variable m11es_run and initialize it to 3. • 85016 o Question 1: Of the following variable names. • 10945 o Write a declaration sta tements to declare and initialize two variables: one is an integer variable names age. 999 4 .50 or 12. 5 .75. and the other variable. • int channel .5.9994. price and cost. measures to the half degree (like 98. val • 10944 5. • 10935 o Write a declaration for a variable temperature that can hold the current outdoor temperature. • 10946 o Write statements to declare and initialize two variables: one. which is element number 8 and has an atomic weight of 15. In the declaration. initialize lhe variable to the values for oxygen . 18 . atomic weights are values l1ke 3. which is the best one for keeping track of whether a patient has a fever or not? • hasFever 4 of 20 2/9/2012 7:19 AM .6 or 31.googleusercontent. numbers (1 -900) and a variable hours_recorded that can hold the number of hours of TV recorded (numbers like 1.5). • reserved • 60106 o Question 1: Which of the following is NOT a legal identifier? • 7thheaven • 60108 o Which of the following IS a legal identifier? 11 4 . double hours_recorded.. • double rate_of_pay. • 10941 o Write a sta tement that declares an int variable age and initializes it to 15. cost . • 10937 o Write a declaration for two variables . named num and val and initializes each to 5. double atomic_weight = 15 .5). • inl age double weight • 60110 o Question 1: Which is the best identifier for a variable to represent the amount of money your boss pays you each month? • monthlyPay • 60118 o Question 1: An identifier that cannot be used as a variable name is a _ _ _ _ word . lhe olher. o Write a statement that declares two int variables. named weight. is initialized to 114. initialized to 18.. • 10932 o Write a declaration for a variable rate_of_pay lhat can hold values like 11. 75 . 5 .0 or 3. • int num . named element_number can hold any integer values 1 through 118.

o X \ 10 5 of 20 2/9/2012 7:19 AM . The length of the smaller one is stored in the variable small.. not a percentage.CgameDev: CodeLab Answers http://webcache.discountAmount • 10530 o GIVen the vanable pricePerCase . the length of the larger one is stored in the variable large. • costOfBusRental I maxBusRiders • 10532 o Write an expression that computes the remainder of the variable principal when divided by the variable divisor. Write an expression whose value is 1 more than x. • x + I or I + x • 11014 o A wall has been built w ith two pieces of sheetrock. (Assume both are type int). a smaller one and a larger one. Write a single expression whose value is the length of this wall. Similar1y.googleusercontent. • taxablePurchases + taxFreePurchases • 10528 o Write and expression that computes the difference of the variables endlngTime and startingTime. • large + small • 11100 o Assume that an lnt variable x that has already been declared. (The variable discountAmount holds the actual amount discounted. • endingTime . wr~e an expression corresponding to the Iota I amount purchased. write an expression corresponding to the cost per rider (assuming the bus is full). o Question 2: Of the following variable names. which is the best one for keeping track of whether an integer might be prime or not? • mightBePrime Express1ons • 10526 o Wnte an expression that computes the sum of two variables verbal Score and math Score (already declared and assigned values). Write and expression whose value is the last (rightmost) digit of x..com/search?q=cache:yuFlRoSgTaMJ.startingTi me • 10529 o Given the variables fuiiAdmissionPrice and discountAmount (already declared and assigned values). write an expression corresponding to the price of a discount admission. write an expression corresponding to the pric of a dozen cases.) • fullAdmissionPrice . • verbalScore + mathScore • 10527 o Given the variables taxablePurchases and taxFreePurchases (already declared and assigned values). • pricePerCase • 12 • 10531 o Given the variables costOfBusRental and maxBusRiders . • 140 + 12 ) I 2 • 10534 o Write and expression that computes the average of the variables exam1 and exam2 (both declared and assigned values). • (examl • exam2) I 2 • 10905 o Assume that an int variable x that has already been declared. • p t inclpal \ divjsor • 10533 o Write an expression that computes the average of the values 12 and 40.

• drivingAge = 17 . 37 Ass1gnments • 10538 o Given an integer variable drivingAge that has already been declared . wr~e a statement that g ives newRecord the same value that old Record has. the length o f the larger ones is the same and is stored in the variable large. wrne a single expression whose value is the total area of the two rooms. write a statement that assigns the value 17 to drivingAge.. • g1adAge • 10955 o Write a s tatement to assign to weight_in_pounds the value o f ma~ricAge + 4.. a smaller one and a larger one. Write a single expression whose value is the total area of this room. Assuming the nem is paid for with a mm1mum amount of change and just single dollars.com/search?q=cache:yuFlRoSgTaMJ. o Given two Integer vanables oldRecord and newRecord .CgameDev: CodeLab Answers http://webcache.oldRecord . write a statement that gives gradAge a value that is 4 more than the value of matrlcAge. 00 NOT use the pow function . Similarly. write an expressiOn for the amount of change (in cents) that would have to be paid. write an expression for the number of single dollars that would have to be paid. write an expression that divides distance by speed using floating point arithmetic. • 10947 o Wnte a statement to set the value of num to 4 (num is a variable that has already been declared).e a fractional resuH should be produced. • num • 10539 4.:~rge !00 100 + small ) • (large + small ) • 60065 o Question 1: Which of the following is NOT an operator? • add o Question 2: Which of the following is NOT an operator? • 60066 o Question 1: Which of the following is NOT an expression? • Pl =3. 6 of 20 2/9/2012 7:19 AM . • price I • 11022 o Assume that price IS an Integer vanable whose value is the price (in US currency) in cents of an item.14159 o Question 2: Which o f the following is NOT an expression? • int prime . • length! • widthl + length2 • width2 • 10608 o Given two mteger variables d istance and speed . Assuming the item is paid for with a minimum amount of change and just single dollars. i. • 11001 o Assume that price is an integer variable whose value is the price (in US currency) in cents of an item. • price \ • 11015 o Each of the walls of a room with square dimensions has been built with two p1eces o f sheetrock. • • 11013 o The dimensions (width and length) of room1 have been read into two variables: width1 and length1 . The dimensions of room2 have been read into two other variables: width2 and length2 . • (double)distance/speed (l.googleusercontent. • 10540 o Given two Integer variables matricAge and gradAge . The length of the small ones is the same and is stored in the variable small. • newRecord .

2 . 2. • circumference • 10951 o Write a sta tement to add the values o f x andy together.14159 and assign the result to circumference . 2 . • ans nwn • 5 . • rem • num \ 5 .. 9The variables have already been declared and cost has already been inrtialiZed). • net pay • qross_pay .googleusercontent. (The variables have already been declared and gross_pay and tax have already been initialized). (The variables have already been declared and weight_in_kilos has already been initialiZed). • 10960 o Wnte a statement using a compound assignment operator to add 5 to val (can 1nteger vanable that has already been declared and initialized).CgameDev: CodeLab Answers http://webcache. • pay I • 10963 o Write a statement using a compound assignment operator to multiple num_rabbits by 4. o Given the integer variable profits .. 5. (The variables have already been declared and pounds has already been initialized). • sum • 10542 X + y. (The vanables have already been declared and num has already been initialized).ta x. (The variables have already been declared and diameter has already been initialized). 7 of 20 2/9/2012 7:19 AM . • profits • . • 10954 o Write a statement to multiple diameter by 3. • num rabbits *= ~. • val • • 10962 o Write a statement using a compound assignment operator to cut the value of pay 1n half (pay is an integer variable that has already been declared and initialized). o Write a statement to set the value of area to the value of length times the value of Width. • 10957 o Write a statement to find the remainder rem when num is divided by S.10. storing the result in sum. 14159 .2. • kilos • 10950 o Write a statement to set the value of price equal to three time the value of cost. (These variables have already been declared and num has already been initialized). • weiqht_in_pounds • weiqht_in_kilos • 2 . • 10949 o Write a statement to set the value of ans equal to the value of num plus 5. (The variables have already been declared and length and width have already been initialized).com/search?q=cache:yuFlRoSgTaMJ. • 10956 o Write a sta tement to assign to kilos the value of pounds divided by 2. changing the value of num_rabbits (num_rabbits has already been declared and initialized). diameter • 3 . • 10952 o Write a statement to subract tax from gross_pay and assign the result to net_pay . • price • 10953 3 • cost . pounds I 2 .2. weight_in_kilos times 2. • area • length • width . write a statement that increases the value of that variable by a factor of 10. (The variables have already been declared and x and y have already been initialized).

write some code that swaps their values.. respectively. Declare any additional variables as necessary." . secondPlaceWinner = temp . The o riginal value of i. write a statement that uses the auto-increment operator to increase the value of that variable by 1. which have been declared. can now be assigned to j . What a re the • s is 20 and t cannot be de termined Constants • 10520 o Declare an int constant MonthslnDecade whose value is the value o f the constant MonthslnYear (already declared) multiplied by 10.CgameDev: CodeLab Answers http://webcache. which was saved in temp . • 10548 o Given two int variables . i j ." . and then copying itemp and j temp to j and i. What value =20. • count --.. Console 1-0 8 of 20 2/9/2012 7:19 AM . p • item = i . but do not redeclare firstPiaceWinner and secondPiaceWin ner. vends up with 20 o Question 2: Consider this code : "int s values of s and t? =20. jtemp • j . firstPlaceWinner • secondPlaceWinner. • 10964 o Write a statement using a compound assignment operator to change val to the remainder when val is divided by 16 (val has already been declared and initialized). • 10549 o Given three already declared int variables.com/search?q=cache:yuFlRoSgTaMJ. • 60128 o Question 1: Consider this code: "int v is printed. jtemp. • 10959 o Write a s tatement using the decrement ope rator to decrease the value of count (an already declared integer variable) by 1. i. which have been declared and initialized. j . • 10544 o Given an integer variable timer . write some code that swaps the values in i and j . write a s tatement that uses the auto-decrement operator to decrease the value of that variable by 1. itemp and jtemp . • num_items++ .googleusercontent. respectively. temp = firstPlaceWinner . and temp . i and j . Use temp to hold the value o f i and then assign j 's value to i. temp . • const int MonthslnDecade • MonthslnYear * 10. • temp • i . • 10543 o Given an integer variable strawsOnCamel . • int temp . int t =s++ + -s. and two other int variables. • 10958 o Write a statement using the increment operator to increase the value of num_items (an a lready declared integer variable) by 1. • timer --. f irstPiaceWinner and secondPiaceWinner . • • 10550 o Given two int variables . j • itemp . • strawsOnCamel++ . write some code that swaps the values in i and j by copying their values to itemp and jtemp . • val \= 16. -v . cout « v++. what value is v left with? • 19 is printed.

the output would be: i = 25 f 12. Assume that first has already been declared as a double and that second has been declared as an int. and then a space. your output should NOT include something like "count=". Write a statement that prints the value of dollars and Y cents". They might be 187 and 25. write a statement that writes the value of count to standard output (When we say "given· . Do not write anything else to standard output-. So. write a statement that wr~es the value of fraction to standard output. In particular.CgameDev: CodeLab Answers http://webcache. Remember: In your output you must be displaying both the name of the variable (like i) and its value. if i's value were 25 and fs value were 12. If that's What their value are. • 10968 o Write a sta tement that reads a floating point (real) value from standard input into temperature. followed by "second the value of second.06. Assume also that the variables have already been given values.. << count .just the value of count. • 10505 o Given an integer variable count. be sure to scroll down to read everything. << endl .34. • cout << "i " << i << "f• " << f . Just write one statement to produce the output. 9 of 20 2/9/2012 7:19 AM . Assume tha t temperature has already been declared as a double variable.just the value of fraction. • 6 • 11023 o Assume that price is an integer variable whose value is the price (in US currency) in cents of an item. Given an integer variable i and a floating-point variable f.. =•. ·x • cout << price/100 << "dollars and " << price\100 << " cents". your code would print "43 dollars and 21 cents". • cout << '' first is '' << fi rst <<" second • '' << second • 60103 o Question 1: How many spaces printed out by this statement: cout « "how" << "now"<< "brown"<< "cow" << "?".googleusercontent.so you should not declare it!) Do not wnte anything else to standard output.06 Remember: You are GIVEN i and f --that means they are already declared and they already have values! Don't change their values by aSSIQmng or initialiZing them! Just print them out the way we have shown above. • 0 o Question 2: How many spaces printed out by this statement: cout « "abc\ndel\tghi\njkr « endl « endl « "mno\n\npqr\n". Print everything on one line and go to a new tine after printing. • 10966 o Write a single statement that w ill print the message "first is • followed by followed by the value of first.34 = But you don1 know what i's value and fs value are. If you see an internal scroll bar to the right o f these instructions. • count • 10506 o Given a floating-point variable fraction . The output should be JUST the value of the variable count.please read them all carefully. • 10507 o The exercise instructions here are LONG . If the value was 501 it would print "5 dollars and 1 cents".com/search?q=cache:yuFlRoSgTaMJ. the output from your statement should be: i = 187 f = 24. if the value of price was price in the form 4321 . If the value was 99 your code would print ·o dollars and 99 cents". that means that count has ALREADY been declared . w rite a statement that writes both of their values to standard output in the following format: i = value-of-i f = value-of-f Thus. • cout << fraction .

NAM E!!!" where NAME is replaced the value that was read into name.Reads a value from the keyboard into the variable -Writes to standard output the variable's value. • 10515 o Write a complete program that . "Alexandra" and "Zoe") and ages respectively.googleusercontent.CgameDev: CodeLab Answers http://webcache. that has already been declared." • cin >> name >> age ." << name . Write some code that reads in a name and an age and then prints the message ''The age of NAME is AGE. For example. cout << k << " " << k "' 2 << " " << k ". • cin >> name . Comments 10 of 20 2/9/2012 7:19 AM .Declares an integer variable . • finclude <iostream> using namespace std . • cin >> val .Rachel". Write some code that reads a value into name then prints the message "Greeting. • c in >> firstWord . Besides the numbers." << name << n! ! 11 ! ". Write some code that reads a value into name then prints the message "Greetings. Assume that val has already been declared as an int variable. twice the value .k. i nt main() int k. x. "Fritz" and "Moustafa"). • 11006 o Write a statement that reads a word from standard input into firstWord.NAME" where NAME is replaced the value that was read into name. nothing else should be written to standard output except for spaces separating the values.. • 10978 o Write an expression that attempts to read an integer from standard input and store it in an int variable. cin >> k. • cin >> temperature. if your code read in "Hassan" it would print out "Greetings. • 10967 o Write a statement that reads an integer value from standard input into val. if your code read in "Rachel" it would print out "Greeting. cout << "Greetings . Hassaon!!l". For example.. • cin >> name .com/search?q=cache:yuFlRoSgTaMJ." where NAME and AGE are replaced by the values read in for the variables name and age. if your code read in "Rphit" and 70 then it would print out "The age of Rohit is 70. • cin >> x . cout << '"rhe age of " << name << " is " << age (( II n • • 11010 o Assume that name has been declared suitably for storing names (like "Misha" . For example. separated by spaces. • 11009 o Assume that name and age have been declared suitably for storing names (like "Abdullah" . "Emily" and "Sofia"). • 11011 o Assume that name has been declared suitably for storing names (like "Amy" . cout << Greetings . and the square of the value. Assume hat firstWord has already been declared as a char array large enough to hold a 50-letter-word.

..com/search?q=cache:yuFlRoSgTaMJ.CgameDev: CodeLab Answers http://webcache. 11 of 20 2/9/2012 7:19 AM .googleusercontent.

base . and acid .. the message "tie" is printed and the variable tieCount IS incremented. false if pH is equal to 7 • i f (pH < 7) I neutral = false .CgameDev: CodeLab Answers http://webcache. player2Wins . base acid • false . player2Lossess++. o Clunker Motors Inc. Given a variable modeiYear and a string model Name wnte a statement that pnnts the message "RECALL· to standard output 1f the values of modeiYear and model Name match the recall detatls. i ! (score2 > scorel) ( coul << "player2 wins ".com/search?q=cache:yuFlRoSgTaMJ.googleusercontent. false. false. • i f (modelName modelYear && "Extravagant" && 1999 <• "Guzzler " modelYear <• 2002 II modelName "2004 <• modelYear && • 11072 modelYear <= 2007) cout << " RECALL" << endl . A bool variable named recalled has been declared . player2Losses .0 and makes the followmg assignments to the boot variables neutral . When score1 exceeds score2 • the message "player1 wins" is printed to standard out. • if (scorel > score2) I cout << "playerl wins ". F1nally. the vanables player1Wins . Do not use an if statement in this exercise! 12 of 20 2/9/2012 7:19 AM . are Incremented when appropriate. playerlWins++. actd • false . false If pH ts greater than 7 true. e l se coul << "tie ". player2Wins++. in the event of a be.. if ( p H •• 7 ) I neutral • true . f Multrway 1 else • 10568 o Wnte an if/else statement that compares the double variable pH with 7. IS recalling all vehicles in its Extravagant line from model years 1999-2002 as well all vehicles in its Guzzler line from model years 2004-2007. LieCount++ . acid . true 1f pH is less than 7 false. false. playerlLosses++. • 11063 o Write a statement that compares the values of score1 and score2 and takes the following acbons. Given a variable modeiYear and a string modeiName write a statement that assign true to recalled if the values of modeiYear and model Name match the recall details and assigns false otherwise. true . is recalling all vehicles in its Extravagant tine from model years 1999-2002 as well all vehicles in ~s Guzzler line from model years 2004-2007. true.true . player1Losses . false . In each case. When score2 exceeds score1 • the message "player2 wins· is printed to standard out. i f (pH > 7) neutral b«se false . • 11071 o Clunker Motors Inc. !ever false . base • false .

and burger respectively. asparagus T: whole trout.CgameDev: CodeLab Answers http://webcache. • 11064 o Online Book Merchants offers premium customers 1 free book with every purchase of 5 or more books and offers 2 free books with every purchase of 8 or more books. red potatoes. brussel sprouts 8 : cheddar cheeseburger. • i f (isPremiumCustomer) i f (nbooksPurchased >• 8) freeBooks = 2 ..2001) . Assume further that the user has just been presented With the folloWing menu: S: hanger steak. else i f (choice== ' T ' ) cout << "cranberry juice". • recalled - (modelName == " Ex travagant " H 1999 <• modelYear && modelYear " Gizzler " && 2004 <• 2002 I I model Name <• modelYear && modelYear <. this menu really IS a menu!) Write some code that reads the character (S or T or B) that the user types in into a char variable choice that has already been declared and prints out a recommended accompanying drink as follows: if the value of age is 21 or lower. and offers 2 free books with every purchase of 12 or more books. Regardless of the value of age . freeBooks else free8ooks • 0 . trout. else i f (choice •• ' 8 ' ) cout << "soda". long rice. Write a statement that assigns freeBooks the appropriate value based on the values of the bool variable isPremiumCustomer and the int variable nbooksPurchased . "cranberry juice" for trout. else if (choice •• ' S ' ) cout << "cabernet ". Otherwise. else freeBooks • 0. else i f (nbooksPurchased >= 12) freeBooks = 2 . • 11079 o Assume that an int variable age has been declared and already given a value. the recommendations are "cabernet". else i f (nbooksPurchased >= 5) 1.googleusercontent. i f (age <• 21) i f (choice== ' S ' ) cout << "vegetable juice". else cout << "invalid menu selection". steak fries. and "IPA" for steak.com/search?q=cache:yuFlRoSgTaMJ. "chardonnay". and "soda" for the burger. else e cout << '' invalid m nu selection".. else i f (nbooksPurchased >= 1 ) free Books • 1. the recommendation is "vegetable juice" for steak. 13 of 20 2/9/2012 7:19 AM . • cin >> choice . else i f (choice== ' T ' ) cout << nchardonnay". your code should print "invalid menu selection" if the character read into choice was not S or TorS. It offers regular customers 1 free book with every purchase of 7 or more books. else i f (choice •• ' 8 ' ) cout << "IPA'' . cole slaw (Yes.

.. 14 of 20 2/9/2012 7:19 AM .CgameDev: CodeLab Answers http://webcache.com/search?q=cache:yuFlRoSgTaMJ.googleusercontent.

OK (fulfilled) 403. brea k. break.CgameDev: CodeLab Answers http://webcache. case 8 : case 9 : case 10 : cout << '' elementary". forbidden 404 . middle 13. break. early childhood 6-7 . default : cout << '' inelig ibl e ". break. children are classified by age as follows: less than 2. break. not found 500. break. case 6 : case 7 : cout << "young reader"..googleusercontent. brea k. server error Given an 1nt variable status .e. case 14 : case 15 : case 16 : cout << "high school". case 13 : cout << " i~possible ". case 500 : cout << '' server error". • switch (status) ( case 200 : cout << "OK (fulfilled) ". • 11074 o HTTP is the protocol that governs communications between web servers and web clients (i . break. browsers). 15 of 20 2/9/2012 7:19 AM . case 17 : case 18 : cout << '' scholar ''. brea k. case 404: cout << "not found ". high school • switch (age) case 2 : cout << " toddler ". ineligible 2. ImposSible 14-16. young reader 8-10. toddler 3-5.. break. case 3 : case 4 : case 5 : cout << "early childhood". break. Part of the protocol includes a status code returned by the server to tell the browser the status of its most recent page request. elementary 11 and 12. o In the Happy Valley School System.com/search?q=cache:yuFlRoSgTaMJ. wrne a swnch statement that prints out the appropnate labet from the above list based on status . case 403 : cout << n forbidden tl. Some of the codes and their meanings are listed below: 200. break. case 11 : case 12 : cout << "middle ".

The funcbon returns no value. in file .com/search?q=cache:yuFlRoSgTaMJ. public : 16 of 20 2/9/2012 7:19 AM . associate it with a file named wlnterdata. open {" winterdata . cin >> n. and fstreams • 11054 o Read first a user's given name followed by the user's age from standard input. total + x .. int total 0 . x .txt by opening the file for reading. . cin >> name . int age .A data member score of type i nt . for (int i -0 .A member function called setScore that accepts a parameter and assigns it to score . cin >> age . int score . • string oneSpace • '' '' · • 10720 o Write an expression that whose value is the fifth character o f the string names. • class Player { private : string name .googleusercontent. close( l. ope n ( "outdata ".A member function called getName that accepts no parameters and returns the value of name . Strings. t x t ") .A data member name of type string . . . break . • name [ 4 I • 11171 o Write a full class definition for a class named Player . Assume that this is the extent of the output that this program will do. • ifstream infile . • 11126 o Given the availability of a fi le named numbers write the statements necessary to read an integer from standard input and then read in that many values from numbers and display their total.CgameDev: CodeLab Answers http://webcache. int n . • 11045 o Given an ifstream object named input1 . outdata . • 10844 o Declare a string variable named oneS pace . i<n . ios : : out) : outdata << name << " " << age << endl .A member function called setName that accepts a parameter and assigns 1t to name . cout << total << endl . Then use an ofstream object named outdata to write this information separated by a space into a file called outdata . and initialize it to a string consisting of a single space.. outdata . • inpull .A member function called getScore that accepts no parameters and returns the value of score . and containing the following members: . The function returns no value . Classes. open ( " numbers " ) . . • string name . i++) infile >> x .

). and increments the value of 17 of 20 2/9/2012 7:19 AM . getSum returns the value of sum . void setN ame (string) . e • 11174 o Write a fu!l class definition for a class named Counter • and containing the fo!lowing members: -A data member counter of type int . void Counter : :decrement( ) counter--. add increases the value of sum by the value of the parameter. void Player : : setScore(int s) score = s . -A function ca!led getValue that accepts no parameters. The constructo r initializes the data members sum and the data member count to 0. -A function ca!led decrement that accepts no parameters and returns no value. -A construclor that takes one int argument and assigns its value to counter -A function ca!led inc rement that accepts no parameters and returns no value. public : Counter(int) . void increment () . int getValue () . It returns the value of the instance variable counter ..googleusercontent. and containing the fo!lowing members: -An data member named sum of type integer. void decrement () . -A constructor w ith no parameters. Increment adds one to the counter data member. -An data member named count of type integer..com/search?q=cache:yuFlRoSgTaMJ. void Player : : setN ame (string n) name • n. int getScore () . • 11182 o Write a fu(l class definition for a class named Averager .CgameDev: CodeLab Answers http://webcache. -A function named add that accepts an integer parameter and returns no value. Counter : : Counter (int i ) : counter(i) { } void Counter : : increment( ) counter++ . • class Counter ( private : i n t counter . string Player : : getN ame () ( return nam . string getN ame () . -A function named getSum that accepts no parameters and returns an integer. Decrement subtracts one to the counter data member. void setScore(int) . ).

that Is. + . • do c o ut << "•"· n--. 18 of 20 2/9/2012 7:19 AM . double getAverage ( ).while loop to print a single line consisting of n asterisks. sum( O). • 10585 o Assume the lnt variables I .com/search?q=cache:yuFlRoSgTaMJ. Other Codelab answers that I have • 10581 o Given an int variable n that has already been declared and initialized to a posttive value. .googleusercontent. • while (n < 1 II n > 10) ( cin >> n ..CgameDev: CodeLab Answers http://webcache. hi .. public : Ave r ager () . void add (int ). inl Averager : : getCount() return count . getAverage returns the average of the values added to sum . double Averager:: getAve r age () return (( doubl e ) s um) I count . Thus if n contatns 5. use a do.A functiOn named getAverage that accepts no parameters and returns a double. while (n > 0) . in l getSum () . . • class Averager ( private : int sum . int getco unt () .A function named getcount that accepts no parameters and returns an Integer. count . count (O) ( ) vo id Averager :: add(int val) sum -+• val . Use no variables other than n and j . write some code that repeatedly reads a value into n until at last a number between 1 and 10 (tnclusive) has been entered. 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). count by one. getCount returns the value of the count data member. • 11127 o Given an tnt variable n that has already been declared. Averager :: Averager () int Averager :: getSum( ) return sum . co unt . and another int variable j that has already been declared. and result have been declared and that to and hi have been initialized.. ). the number of values added to sum . to ... five astensks will be printed.

and result . Thus. which has a char parameter and returns nothing. the function prints no opinio nlf the parameter equals 3. passing it the value 14. the function prints disagree!! the parameter equals 2. which has an int parameter and returns nothing. the function print out Grade: A • void printGrade (char x ) cout { << " Grade : " << x << endl . i++) result +. i f (x••2 ) cout << "no opin ion" << e nd l . the function does nothing.i .use only i . i f (x••3 ) cout << "agree" << endl. • printTodaysOate( ) . • 10656 o Write the definition of a function printAttitude . cout << "disagree" << endl . i <= hi . which has two int parameters and returns no value. if the value of the parameter is 'A'. have already been declared an initialized. Wnte a statement that calls printTodaysOate . Also. Write a statement that calls add to compute the sum of euroSales and aslaSales and store this value in eurasiaSales . do not declare any additional variables. • 10639 o prlntTodaysOate IS a function that accepts no parameters and returns no value. • 10655 o Write the definition of a function printGrade . and stores the result in result .googleusercontent. lo . Another int variable. Don't forget to put a new line character at the end of your line. • 10640 o prlntErrorOescription is a function that accepts one int parameter and returns no value. has already been declared. The function prints a message to standard output depending on the value of its parameter. asiaSales ) . hi . the function prints agree In the case of other values. euroSales and asiaSales . Write a for loop that adds the integers between lo and hi (inclusive). MORE COM ING SOON! 19 of 20 2/9/2012 7:19 AM . • eurasiaSales • 10648 o Wnte a statement that declares a prototype for a function printlarger . • for (i • lo. • void printLarger( int a . • 10642 o add is a function that accepts two int parameters and returns their sum.CgameDev: CodeLab Answers http://webcache. Each message is printed on a line by itself. Your code should bot change the values of lo and hi .. • pri n tEr r orOescrip tion( l 4). eurasiaSales ..com/search?q=cache:yuFlRoSgTaMJ. • void printAtt i t ude (in t x) if (X 1) { = add ( euroSales . int b ) . If the parameter equals 1. The function prints on a line by itself the message string Grade: followed by the char parameter (printed as a character) to standard output. Write a statement that calls the function prlntErrorOescription . Two lnt variables.

Simple template.googleusercontent..CgameDev: CodeLab Answers http://webcache. Recommend this on Go ogle Home Subscribe to: Posts (Atom) Public Slog. 20 of 20 2/9/2012 7:19 AM .com/search?q=cache:yuFlRoSgTaMJ.. Powered by Blogger.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.