Monday, June 18, 2012

Homework 6: do_while

1. Given an  int variable  k that has already been declared, use a  do...while loop to print a single line consisting of 97 asterisks. Use no variables other than  k .

k = 0 ; do { cout << "*" ; k ++ ; } while ( k < 97 ) ;

2. Given an  int variable  n that has already been declared and initialized to a positive 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 contains 5, five asterisks will be printed. Use no variables other than  n and  j . 

j = 0 ; do { cout << "*" ; j ++ ; } while ( j < n ) ;

3. Given  int variables  k and  total that have already been declared, use a  do...while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in  total . Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into  total . Use no variables other than  k and  total .

total = 0 ; k = 1 ; do { total += k * k ; k ++ ; } while ( k <= 50 ) ;

4. Given an  int variable  n that has been initialized to a positive value and, in addition,  int variables  k and  total that have already been declared, use a  do...while loop to compute the sum of the cubes of the first  n whole numbers, and store this value in  total . Thus if  n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into  total . Use no variables other than  n ,  k , and  total . 

total = 0 ; k = 1 ; do { total += k * k * k ; k ++ ; } while ( k <= n ) ;

Homework 6: RunningTotal

1. Write a statement that increments the value of the  int variable  total by the value of the  int variable  amount . That is, add the value of  amount to  total and assign the result to  total .

total = total + amount ;

2. Given that two  int variables,  total and  amount , have been declared, write a sequence of statements that: 
 initializes  total to 0 reads three values into  amount , one at a time. After each value is read in to  amount , it is added to the value in  total (that is,  total is incremented by the value in  amount ). 

total = 0 ; cin >> amount ; total += amount ; cin >> amount ; total += amount ; cin >> amount ; total += amount ;

3. Given that two int variables, total and amount, have been declared, write a loop that reads integers into amount and adds all the non-negative values into total. The loop terminates when a value less than 0 is read into amount. Don't forget to initialize total to 0.

total = 0 ; cin >> amount ; while ( amount >= 0 ) { total += amount ; cin >> amount ; }

Homework 6: Literals-2

1. Write a literal representing the false value in C++.

false

2. Write a literal representing the true value.

true

Homework 6: Operations-2

1. Write an expression that evaluates to true if and only if the value of the integer variable  x is equal to zero.

x==0

2. Write an expression that evaluates to true if and only if the variables  profits and  losses are exactly equal.


profits == losses

3. Given the  char variable  c , write an expression that is true if and only if the value of  c is not the space character. 

c != '`'

4. Write an expression that evaluates to true if the value of  index is greater than the value of  lastIndex . 

index > lastIndex

5. Working overtime is defined as having worked more than 40 hours during the week. Given the variable  hoursWorked , write an expression that evaluates to true if the employee worked overtime. 

hoursWorked > 40

6. Write an expression that evaluates to true if the value  x is greater than or equal to  y . 

x >= y

7. Given the variables  numberOfMen and  numberOfWomen , write an expression that evaluates to true if the number of men is greater than or equal to the number of women. 

numberOfMen >= numberOfWomen

8. Given a  double variable called  average , write an expression that is true if and only if the variable's value is less than 60.0. 

average < 60.0

9. Given an  int variable  grossPay , write an expression that evaluates to true if and only if the value of  grossPay is less than 10,000. 

grossPay < 10000


Homework 6: Declarations-3

1. Declare a variable  isACustomer , suitable for representing a true or false value.

bool isACustomer ;

Homework 5: Compound Conditions

1. Given the variables  temperature and  humidity , write an expression that evaluates to true if and only if the temperature is greater than  90 and the humidity is less than  10 .

temperature > 90 && humidity < 10

2. Given the integer variables  yearsWithCompany and  department , write an expression that evaluates to true if  yearsWithCompany is less than  5 and  department is not equal to  99 .

yearsWithCompany < 5 && department != 99

3. Given the boolean variable  isFullTimeStudent and the integer variable  age , write an expression that evaluates to true if  age is less than  19 or  isFullTimeStudent is true.

age < 19 || isFullTimeStudent

4. Write an expression that evaluates to true if and only if the value of the boolean variable  isAMember is false. 

isAMember == false

Homework 5: Cascaded

1. Write an if/else statement that adds  1 to the variable  minors if the variable  age is less than  18 , adds  1 to the variable  adults if  age is  18 through  64 , and adds  1 to the variable  seniors if  age is  65 or older.

if ( age < 18 ) minors ++ ; else if ( age < 65 ) adults ++ ; else seniors ++ ;

2. Write an if/else statement that compares the  double variable  pH with  7.0 and makes the following assignments to the  bool variables  neutral ,  base , and  acid :  false, false, true if  pH is less than  7; false, true, false if  pH is greater than  7;  true, false, false if  pH is equal to  7

if ( pH < 7 ) { neutral = false ; base = false ; acid = true ; } else if ( pH > 7 ) { neutral = false ; base = true ; acid = false ; } else { neutral = true ; base = false ; acid = false ; }

Homework 5: for

1. Given an  int variable  k that has already been declared, use a  for loop  to print a single line consisting of 97 asterisks. Use no variables other than  k .

for ( k = 0 ; k < 97 ; k ++ ) { cout << "*" ; }

2. Given an  int variable  n that has already been declared and initialized to a positive value, and another  int variable  j that has already been declared, use a  for loop to print a single line consisting of  n asterisks. Thus if  n contains 5, five asterisks will be printed. Use no variables other than  n and  j . 

for ( j = 0 ; j < n ; j ++ ) { cout << "*" ; }

3. Given  int variables  k and  total that have already been declared, use a  for loop to compute the sum of the squares of the first 50 counting numbers, and store this value in  total . Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into  total . Use no variables other than  k and  total . 

total = 0 ; for ( k = 1 ; k <= 50 ; k ++ ) total += k * k ;

4. Given an  int variable  n that has been initialized to a positive value and, in addition,  int variables  k and  total that have already been declared, use a  for loop to compute the sum of the cubes of the first  n whole numbers, and store this value in  total . Thus if  n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into  total . Use no variables other than  n ,  k , and  total . 

total = 0 ; for ( k = 1 ; k <= n ; k ++ ) { total += k * k * k ; }

Homework 5: while

1. Given an  int variable  k that has already been declared, use a  while loop to print a single line consisting of 97 asterisks. Use no variables other than  k .

k = 0 ; while ( k < 97 ) { cout << "*" ; k ++ ; }

2. Given an  int variable  n that has already been declared and initialized to a positive value, and another  int variable  j that has already been declared, use a  while loop to print a single line consisting of  n asterisks. Thus if  n contains 5, five asterisks will be printed. Use no variables other than  n and  j . Instructor's notes: Try solving this both with and without using the variable j.

j = 0 ; while ( j < n ) { cout << "*" ; j ++ ; }

3. Given  int variables  k and  total that have already been declared, use a  while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in  total . Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into  total . Use no variables other than  k and  total . 

total = 0 ; k = 1 ; while ( k <= 50 ) { total += k * k ; k ++ ; }

4. Given an  int variable  n that has been initialized to a positive value and, in addition,  int variables  k and  total that have already been declared, use a  while loop to compute the sum of the cubes of the first  n counting numbers, and store this value in  total . Thus if  n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into  total . Use no variables other than  n ,  k , and  total . Do NOT modify  n . 

total = 0 ; k = 1 ; while ( k <= n ) { total += k * k * k ; k ++ ; }


Homework 5: OddEven

1.  Write an expression that evaluates to true if the integer variable  x contains an even value, and false if it contains an odd value.


x % 2 == 0

Homework 5: Divisibility

1. Write an expression that evaluates to true if the value of the integer variable  numberOfPrizes is divisible (with no remainder) by the integer variable  numberOfParticipants . (Assume that  numberOfParticipants is not zero.)

numberOfPrizes % numberOfParticipants == 0

2.  Write an expression that evaluates to true if the value of the integer variable  widthOfBox is not evenly divisible by the integer variable  widthOfBook . (Assume that  widthOfBook is not zero. Note: evenly divisible means divisible without a non-zero remainder.)

widthOfBox % widthOfBook != 0

Homework 5: Simple_if_else

1. Write an if/else statement that compares the variable  age with  65 , adds  1 to the variable  seniorCitizens if  age is greater than or equal to  65 , and adds  1 to the variable  nonSeniors otherwise.

if ( age >= 65 ) seniorCitizens ++ ; else nonSeniors ++ ;

2.  Write an if/else statement that compares the value of the variables  soldYesterday and  soldToday , and based upon that comparison assigns  salesTrend the value  -1 or  1 .

 -1 represents the case where  soldYesterday is greater than  soldToday ; 1 represents the case where  soldYesterday is not greater than  soldToday . 

if ( soldYesterday > soldToday ) salesTrend = - 1 ; else salesTrend = 1 ;

3. Write an if/else statement that assigns  true to the variable  fever if the variable  temperature is greater than  98.6 ; otherwise it assigns  false to  fever . 

if ( temperature > 98.6 ) fever = true ; else fever = false ;

Homework 5: Conditions-Simple

1. Write an expression that evaluates to true if and only if the integer  x is greater than the integer  y .

x > y

2.  Write an expression that evaluates to true if and only if the value of the boolean variable  workedOvertime is true.

workedOvertime == true

Homework 4: Simple_if

1. Write a conditional that assigns  true to the variable  fever if the variable  temperature is greater than  98.6 .


if ( temperature > 98.6 ) fever = true ;

2. Write a conditional that assigns  10,000 to the variable  bonus if the value of the variable  goodsSold is greater than  500,000 . 

if ( goodsSold > 500000 ) bonus = 10000 ;

3.  Write a conditional that decreases the variable  shelfLife by  4 if the variable  outsideTemperature is greater than  90 . 

if ( outsideTemperature > 90 ) shelfLife = shelfLife - 4 ;

4.  Write a conditional that multiplies the values of the variable  pay by one-and-a-half if the value of the boolean variable  workedOvertime is true. 

if ( workedOvertime == true ) pay = pay * 1.5 ;

Homework 4: Precedence-1

1. Write an expression that computes the average of the values  12 and  40 .


( 12 + 40 ) / 2

2. Write an expression that computes the average of the variables  exam1 and  exam2 (both declared and assigned values). 

( exam1 + exam2 ) / 2

Homework 4: Operations-2

1. Given the variable  pricePerCase , write an expression corresponding to the price of a dozen cases.

pricePerCase * 12

2. Given the variables  costOfBusRental and  maxBusRiders , write an expression corresponding to the cost per rider (assuming the bus is full).

costOfBusRental / maxBusRiders

3. Assume that  children is an integer variable containing the number of children in a community and that  families is an integer variable containing the number of families in the same community. Write an expression whose value is the average number of children per family. 

( double ) children / families

4. Write an expression that computes the remainder of the variable  principal when divided by the variable  divisor . (Assume both are type  int .) 

principal % divisor

5.  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 amount of change (in cents) that would have to be paid. 

price % 100


Homework 4: Constants

1. Declare an  int constant,  MonthsInYear , whose value is  12 .

const int MonthsInYear = 12 ;

2.  Declare an  int constant  MonthsInDecade whose value is the value of the constant  MonthsInYear (already declared) multiplied by  10 .


const int MonthsInDecade = MonthsInYear * 10 ;

Homework 4: Literals-1

1.  Write a literal representing the integer value zero.

0

2. Write a floating point literal corresponding to the value zero. 

0.0

3.  Write a literal corresponding to the floating point value one-and-a-half. 

1.5

4.  Write a literal corresponding to the value of the first 6 digits of PI ("three point one four one five nine"). 

3.14159

Homework 3: String Manipulators

1. Write the necessary preprocessor directive to enable the use of the stream manipulators like setw and setprecision.

# include <iomanip>

2. Assume that  m is an int variable that has been given a value. Write a statement that prints it out in a print field of 10 positions.

cout << setw (10) << m ;

3. Assume that  x is a double variable that has been given a value. Write a statement that prints it out with exactly three digits to the right of the decimal point no matter what how big or miniscule its value is.

cout << setprecision ( 3) << fixed << x ;

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

 |xxxxxxx27987654321xxxx-4321

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

cout << setw (9) << k << setw (9) << m << setw (9) << n ;

Homework 3: StringObjects-2

1.  Write an expression that concatenates the string variable  suffix onto the end of the string variable  prefix .


prefix + suffix

2. Given the string variable  address , write an expression that returns the position of the first occurrence of the string "Avenue" in  address .
 
address . find ( "Avenue" )

3. Given a string variable  address , write a string expression consisting of the string "http://" concatenated with the variable's string value. So, if the value of the variable were "www.turingscraft.com", the value of the expression would be "http://www.turingscraft.com".

"http://" + address

4.  Given a string variable  word , write a string expression that parenthesizes the value of  word . So, if  word contains "sadly", the value of the expression would be the string "(sadly)"

"(" + word + ")"

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

name. substr ( name. length ( ) - 1 )

6.  Assume that  sentence is a variable of type  string that has been assigned a value. Assume furthermore that this value is a string consisting of words separated by single space characters with a period at the end. For example: "This is a possible value of sentence." 

 Assume that there is another variable declared,  firstWord , also of type  string . Write the statements needed so that the first word of the value of  sentence is assigned to  firstWord . So, if the value of  sentence were "Broccoli is delicious." your code would assign the value "Broccoli" to  firstWord . 

firstWord = sentence. substr ( 0 , sentence. find ( "`" ) ) ;

7. Assume that  sentence is a variable of type  string that has been assigned a value. Assume furthermore that this value is a string consisting of words separated by single space characters with a period at the end. For example: "This is a possible value of sentence." 

 Assume that there is another variable declared,  secondWord , also of type  string . Write the statements needed so that the second word of the value of  sentence is assigned to  secondWord . So, if the value of  sentence were "Broccoli is delicious." your code would assign the value "is" to  secondWord . 

secondWord = sentence.substr (sentence.find ("`") + 1); secondWord = secondWord.substr (0, secondWord.find ("`"));


Homework 3: StringObjects-1

1. Declare a string variable named  str and initialize it to  Hello .

string str = "Hello" ;

2. Write an expression that results in a string consisting of the third through tenth characters of the string  s .

s . substr ( 2 , 8 )

3. Write a sequence of statements that finds the first comma in the string  line , and assigns to the variable  clause the portion of  line up to, but not including the comma. You may assume that an int variable  pos , as well as the variables  line and  clause , have already been declared. 

pos = line . find ( "," ) ; clause = line . substr ( 0 , pos ) ;

Homework 3: Operations-1

1. Write an expression that computes the sum of the two variables  verbalScore and  mathScore (already declared and assigned values).

verbalScore + mathScore

2. Given the variables  taxablePurchases and  taxFreePurchases (already declared and assigned values), write an expression corresponding to the total amount purchased.

taxablePurchases + taxFreePurchases

3. Write an expression that computes the difference of the variables  endingTime and  startingTime .

endingTime - startingTime

4. Given the variables  fullAdmissionPrice and  discountAmount (already declared and assigned values), write an expression corresponding to the price of a discount admission. (The variable  discountAmount holds the actual amount discounted, not a percentage.) 

fullAdmissionPrice - discountAmount

Homework 3: Programs

1.  Write a complete program that declares an integer variable, reads a value from the keyboard into that variable, and writes to standard output the square of the variable's value. Besides the number, nothing else should be written to standard output.

# include <iostream> using namespace std ; int main ( ) { int x ; cin >> x ; cout << x * x ; return 0 ; }

2. Write a complete program that declares an integer variable, reads a value from the keyboard into that variable, and 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.

# include <iostream> using namespace std ; int main ( ) { int x ; cin >> x ; cout << x << "`" << 2 * x << "`" << x * x ; return 0 ; }

Homework 2: Assignment

1. Given an integer variable  drivingAge that has already been declared, write a statement that assigns the value 17 to  drivingAge .

drivingAge = 17 ;

2.  Given two integer variables  oldRecord and  newRecord , write a statement that gives  newRecord the same value that  oldRecord has.

newRecord = oldRecord ;

3. Given two integer variables  matricAge and  gradAge , write a statement that gives  gradAge a value that is 4 more than the value of  matricAge .  

gradAge = matricAge + 4 ;

4. Given an integer variable  bridgePlayers , write an statement that increases the value of that variable by 4. 

bridgePlayers= 4 + bridgePlayers;

5. Given an integer variable  profits , write a statement that increases the value of that variable by a factor of 10. 

profits = profits * 10 ;

6. Given an integer variable  strawsOnCamel , write a statement that uses the auto-increment operator to increase the value of that variable by 1. 

strawsOnCamel ++ ;

7. Given an integer variable  timer , write a statement that uses the auto-decrement operator to decrease the value of that variable by 1. 

timer --;

Homework 2: Input

1. Given an  int variable  datum that has already been declared, write a statement that reads an integer value from standard input into this variable.

cin >> datum ;

2.  Write an expression that attempts to read a double value from standard input and store it in an double variable, x, that has already been declared.

cin >> x;


Homework 2: Output

1. Given an integer variable count, write a statement that writes the value of count to standard output.

cout << count;

2. Given a floating-point variable  fraction , write a statement that writes the value of  fraction to standard output.

 Do not write anything else to standard output -- just the value of  fraction .

cout << fraction ;

3. Given an integer variable i and a floating-point variable f, write 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 has the value 25 and f has the value 12.34, the output would be:

i=25 f=12.34

 But if i has the value 187 and f has the value 24.06, the output would be:

i=187 f=24.06

Instructor's notes: Don't forget to output a space between i=value-of-i and  f=value-of-f


cout << "i=" << i << "`f=" << f ;

Homework 2: Initialization

1. Declare an integer variable  cardsInHand and initialize it to 13.

int cardsInHand = 13 ;

2.  Declare a variable  temperature and initialize it to 98.6.

double temperature = 98.6 ;

3. Declare a numerical variable  precise and initialize it to the value 1.09388641.

double precise = 1.09388641 ;

4.  Declare and initialize the following variables: 
A variable  monthOfYear , initialized to the value 11
A variable  companyRevenue , initialized to the value 5666777
A variable  firstClassTicketPrice , initialized to the value 6000
A variable  totalPopulation , initialized to the value 1222333

int monthOfYear = 11 ; int companyRevenue = 5666777 ; int firstClassTicketPrice = 6000 ; int totalPopulation = 1222333 ;

Homework 2: Declarations

1. Declare an integer variable named  degreesCelsius .

int degreesCelsius;

2.  Declare two integer variables named  profitStartOfQuarter and  cashFlowEndOfYear . 

int profitStartOfQuarter ; int cashFlowEndOfYear ;

Homework 2: Basics

1.  Declare a variable  populationChange , suitable for holding numbers like -593142 and 8930522.

int populationChange;

2.  Declare a variable  x , suitable for storing values like 3.14159 and 6.02E23. 
double x ;

Homework 1

Intro:

1. Write a statement that prints  Hello World to the screen. 

cout << "Hello World " <<endl;

2.  Write a complete program that prints  Hello World to the screen. 

#include <iostream>
using namespace std;

int main()
{
cout << "Hello World " <<endl;
return 0;
}

3.  Suppose your name was Alan Turing. Write a statement that would print your last name, followed by a comma, followed by your first name. Do not print anything else (that includes blanks). 

cout << "Turing,Alan " <<endl;

4.  Suppose your name was George Gershwin. Write a complete program that would print your last name, followed by a comma, followed by your first name. Do not print anything else (that includes blanks). 

#include <iostream>
using namespace std;

int main()
{
cout << "Gershwin,George " <<endl;
return 0;
}