CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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 Text-only version
1 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
2 of 20
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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 initialize~ to 13. • int cardslnHand
=
13 ;
• 10511 o Declare a vanable temperature and
in~ialize
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. 15; • inl age 90 ; inl weight
• 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 • int year
in~ialize ~to
365.
365 ;
• 10938 o Write a declaration for an integer variable area and a variable price that can hold numbers with decimal places. • int area ; double price ;
• 10939 o Write a declaration for variables length, w idth, 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
3 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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 sta tement 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 . 999 4 ; • 10945 o Write a declaration sta tements 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. 18 ; • inl age double weight
11 4 . 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
4 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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).
• verbalScore + mathScore
• 10527 o Given the variables taxablePurchases and taxFreePurchases (already declared and assigned values). wr~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 fuiiissionPrice and discountAmount (already
declared and assigned values). write an expression corresponding to the price of a discount ission. (The variable discountAmount holds the actual amount discounted, not a percentage.)
• fullissionPrice - 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). • p t 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 int 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 w ith 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 value is the last (rightmost) digit of x. o X \
5 of 20
10
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
• 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. 100
• price \ • 11015
o Each of the walls of a room with square dimensions has been built with two p1eces o f 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 o f 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 . •
(l;:~rge
+ 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 d istance 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 o f the following is NOT an expression? • int prime . 37
Ass1gnments • 10538 o Given an integer variable drivingAge 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 , wr~e a statement that g ives 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
ma~ricAge
+ 4;
• 10955 o Write a s tatement to assign to weight_in_pounds the value o f
6 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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 - ta x; • 10956 o Write a sta tement to assign to kilos the value of pounds divided by 2.2. (The variables have already been declared and pounds has already been initialized). pounds I 2 . 2 ;
• kilos • 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). 3 • cost ;
• price • 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). length • width ;
• area •
• 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 sta tement to add the values o f 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_rabbits has already been declared and initialized).
• num rabbits *=
7 of 20
~;
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
• 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 variable by 1.
• strawsOnCamel++ ; • 10544 o Given an integer variable timer , write a s tatement 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 int 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. • itemp = i ;
jtemp • j ;
jtemp; j
•
itemp ;
• 10549 o Given three already declared int variables, i, j , and temp , write some code that swaps the values in i and j . Use temp to hold the value o f i and then assign j 's value to i. The o riginal value of i, which was saved in temp , can now be assigned to j .
• temp • i ; i j ; •
temp ;
• 10550 o Given two int variables , f irstPiaceWinner and secondPiaceWinner . write some code that swaps their values. Declare any additional variables as necessary, but do not redeclare firstPiaceWinner and secondPiaceWin ner.
• int temp ; temp = firstPlaceWinner ; firstPlaceWinner • secondPlaceWinner; secondPlaceWinner = temp ; • 10958 o Write a statement using the increment operator to increase the value of num_items (an a lready declared integer variable) by 1. • num_items++ ;
• 10959 o Write a s tatement using the decrement ope rator to decrease the value of count (an already declared integer variable) by 1.
• count --; • 60128 o Question 1: Consider this code: "int v is printed, what value is v left with?
=20; -v ; cout «
v++;" . What value
• 19 is printed, vends up with 20 o Question 2: Consider this code : "int s values of s and t?
=20; int t =s++ + -s;" . 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.
• const int MonthslnDecade • MonthslnYear * 10; Console 1-0
8 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
• 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 fraction , write a statement that wr~es 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 o f these instructions, be sure to scroll down to read everything. Given an integer variable i and a floating-point variable f, 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, 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 value are, the output from your statement should be: i = 187 f = 24.06 : 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. : 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 w ill print the message "first is • followed by followed by the value of first, and then a space, followed by "second the value of second. Print everything on one line 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.
=•.
• cout << '' first is '' << fi rst <<" second • '' << second
<< endl ;
• 60103 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 dollars and Y cents". So, if the value of price was price in the form 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".
·x
<< price/100 << "dollars and " << price\100 << " cents";
• cout
• 10968 o Write a sta tement that reads a floating point (real) value from standard input into temperature. Assume tha t temperature has already been declared as a double variable.
9 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
• 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.
• c in >> 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,NAM E!!!" 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 << Greetings ," << name << n! ! 11
! ";
• 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 - Reads a value 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
using namespace std ; i nt main() int k; cin >> k; cout
<< k
<< " " << k "' 2 << " " << k "- k;
Comments
10 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
11 of 20
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
false ;
!ever
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
• i f (pH < 7) I neutral = false ; base • false ; acid - true ;
i f (pH
>
7)
neutral
false ;
true ; actd • false ; b«se
if ( p H •• 7 ) I
neutral • true ; false ; base acid • false ; • 11063
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.
• if (scorel > score2) I cout << "playerl wins ";
playerlWins++; player2Lossess++; i ! (score2 > scorel) ( coul << "player2 wins ";
player2Wins++; playerlLosses++; e l se coul << "tie "; LieCount++ ;
• 11071
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.
• i f (modelName modelYear &&
"Extravagant" && 1999 <•
modelYear <• 2002 II modelName
"2004 <• modelYear &&
"Guzzler "
modelYear <= 2007)
cout << " RECALL" << endl ; • 11072 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!
12 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
• recalled -
(modelName == " Ex travagant " H
1999
<• modelYear && modelYear " Gizzler " && 2004
<• 2002 I I model Name
<• modelYear && modelYear
<- 2001) ; • 11079 o Assume that an int variable age has been declared and already given a value. Assume further that the 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 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.
• cin >> choice ;
<• 21) i f (choice== ' S ' ) cout << "vegetable juice"; else i f (choice== ' T ' ) cout << "cranberry juice"; else i f (choice •• ' 8 ' ) cout << "soda"; else
i f (age
cout << "invalid menu selection"; else
if (choice •• ' S ' ) cout << "cabernet "; else i f (choice== ' T ' )
cout << nchardonnay"; else i f (choice •• ' 8 ' ) cout << "IPA'' ; else
cout << '' invalid me nu selection"; • 11064 o Online Book Merchants offers 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 isCustomer and the int variable nbooksPurchased . • i f (isCustomer) i f (nbooksPurchased >• 8) freeBooks = 2 ; else i f (nbooksPurchased >= 5) 1; freeBooks else free8ooks • 0 ; else i f (nbooksPurchased >= 12) freeBooks = 2 ; else i f (nbooksPurchased >= 1 ) free Books • 1; else freeBooks • 0;
13 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
14 of 20
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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"; brea k; 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 <<
" i~possible ";
break; case 14 : case 15 : case 16 : cout << "high school"; break; case 17 : case 18 : cout
<< '' scholar '';
brea k; default : cout << '' inelig ibl e "; break; • 11074 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 ";
brea k; case 500 : cout << '' server error";
15 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
break ;
Classes, Strings, and fstreams
• 11054 o Read first a 's given name followed by the '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.
• string name ; int age ;
cin >> name ; cin >> age ; outdata . ope n ( "outdata ", ios : : out) : outdata << name << " " << age << endl ; outdata . close( l;
• 11045 o Given an ifstream object named input1 , associate it with a file 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.
• ifstream infile ; in file . open ( " numbers " ) ; int total 0 ; int n , x ; cin >> n;
for (int i -0 ; i
> x ; total + x ; cout << total << endl ;
• 10844 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 fifth character o f the string names.
• name [ 4 I
• 11171 o Write a full class definition for a class named Player , and containing the following : - 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 :
16 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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 ; • 11174 o Write a fu!l class definition for a class named Counter • and containing the fo!lowing : -A data member counter of type int . -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. 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 instance variable counter .
• class Counter ( private : i n t counter ;
public : Counter(int) ; void increment () ; void decrement () ; int getValue () ; );
Counter : : Counter (int i ) : counter(i) { } void Counter : : increment( ) counter++ ;
void Counter : :decrement( ) counter--; • 11182 o Write a fu(l class definition for a class named Averager , and containing the fo!lowing : -An data member named sum of type integer. -An data member named count of type integer. -A constructor w ith no parameters. The constructo r initializes the data sum and the data member count to 0. -A function named getSum that accepts no parameters and returns an integer. getSum returns the value of sum . -A function named add that accepts an integer parameter and returns no value. add increases the value of sum by the value of the parameter, and increments the value of
17 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
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 to double prior to performing the division).
• class Averager ( private : int sum , count ; public :
Ave r ager () ; in l getSum () ; void add (int ); int getco unt () ; double getAverage ( ); );
sum( O), count (O) ( )
Averager :: Averager () int Averager :: getSum( ) return sum ;
vo id Averager :: add(int val) sum -+• val ; co unt .. + ;
inl Averager : : getCount() return count ;
double Averager:: getAve r age () return (( doubl e ) s um) I count ;
Other Codelab answers that I have
• 10581 o Given an int variable n that has already 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. • while (n
<
1 II n
>
10) (
cin >> n ; • 10585 o Assume the lnt variables I , to , hi , and result have been declared and that to and hi have been initialized.
18 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
Write a for loop that adds the integers between lo and hi (inclusive), and stores the result in 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 , ing it the value 14. • pri n tEr 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 printAttitude , 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 disagree!! the parameter equals 2, the function prints no opinio nlf 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 printAtt i t ude (in t x) if (X 1)
cout << "disagree" << endl ; i f (x••2 ) cout << "no opin ion" << e nd l ; i f (x••3 )
cout << "agree" << endl; • 10655 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 line. Thus, if the value of the parameter is 'A', the function print out Grade: A • void printGrade (char x ) cout
{
<< " Grade : " << x << endl ;
MORE COM ING SOON!
19 of 20
2/9/2012 7:19 AM
CgameDev: CodeLab Answers
http://webcache.googlecontent.com/search?q=cache:yuFlRoSgTaMJ...
Recommend this on Go ogle
Home Subscribe to: Posts (Atom)
Public Slog. Simple template. Powered by Blogger.
20 of 20
2/9/2012 7:19 AM