Tuesday, June 19, 2012
Welcome!
If you need help with TuringsCraft codelab for CS 1/C++ you've come to the right place! Go to the right hand side for easy navigation and search button! Make sure you book mark our page or search google for "c plus plus codelab answers" next time you come!
Homework 10: testing
1. Assume you need to test a function named max . The function max receives two int arguments and returns the larger. Write the definition of driver function testmax whose job it is to determine whether max is correct. So testmax returns true if max is correct and returns false otherwise. Instructor's notes: testmax does not take any arguments, only max does. So, the header of testmax will look like this:
bool testmax () { return max ( 5 , 4 ) == 5 && max ( 4 , 5 ) == 5 && max ( 4 , 4 ) == 4; }
bool testmax () { return max ( 5 , 4 ) == 5 && max ( 4 , 5 ) == 5 && max ( 4 , 4 ) == 4; }
2. Assume you need to test a function named inOrder . The function inOrder receives three int arguments and returns true if and only if the arguments are in non-decreasing order: that is, the second argument is not less than the first and the third is not less than the second. Write the definition of driver function testInOrder whose job it is to determine whether inOrder is correct. So testInOrder returns true if inOrder is correct and returns false otherwise.
. For the purposes of this exercise, assume inOrder is an expensive function call, so call it as few times as possible!
bool testInOrder () { return inOrder ( 1 , 2 , 3 ) && inOrder ( 1 , 1 , 3 ) && inOrder ( 1 , 2 , 2 ) && inOrder ( 2 , 2 , 2 ) && !inOrder ( 5 , 2 , 3 ) && !inOrder ( 3 , 4 , 1 ) && !inOrder ( 2 , 1 , 3 ) && !inOrder ( 3 , 2 , 1 ) && !inOrder ( 3 , 1 , 1 ) && !inOrder ( 1 , 3 , 1 ) && !inOrder ( 3 , 3 , 1 ) && !inOrder ( 3 , 1 , 3 ); }
Homework 10: Vectors-2 Vectors (Part 2)
1. Assume that an array of integers named a that contains exactly five elements has been declared and initialized. Write a single statement that assigns a new value to the first element of the array. This new value should be equal to twice the value stored in the last element of the array. Do not modify any values in the array other than the first element. Instructor's notes: An array is used just like a vector, only it does not have any member functions. That means you cannot use the size member function for this exercise, but you do know the size is 5
a [ 0 ] = 2 * a [ 4 ] ;
2. Assume v is a vector that has been declared and initialized. Write an expression whose value is the number of values that have been stored in v.
v . size ( )
3. Assume that an vector of int named a has been declared with 12 elements and that the integer variable k holds a value between 0 and 6. Assign 15 to the vector element whose index is k .
a [ k ] = 15 ;
4. Given that an vector of int named a has been declared, and that the integer variable n contains the number of elements of the vector a , assign -1 to the last element in a . Instructor's notes: Do not use a member function in your solution to this problem.
a [ n - 1 ] = - 1 ;
5. Given that an vector of int named a has been declared with 12 elements and that the integer variable k holds a value between 0 and 6. Assign 9 to the element just after a[k] .
a [ k + 1 ] = 9 ;
6. Given that an array of int named a has been declared with 12 elements and that the integer variable k holds a value between 2 and 8. Assign 22 to the element just before a[k] . Instructor's notes: This question works exactly the same for vectors, so just switch the name array with vector in the exercise description. In other words, think of a as a vector, not an array.
a [ 0 ] = 2 * a [ 4 ] ;
2. Assume v is a vector that has been declared and initialized. Write an expression whose value is the number of values that have been stored in v.
v . size ( )
3. Assume that an vector of int named a has been declared with 12 elements and that the integer variable k holds a value between 0 and 6. Assign 15 to the vector element whose index is k .
a [ k ] = 15 ;
4. Given that an vector of int named a has been declared, and that the integer variable n contains the number of elements of the vector a , assign -1 to the last element in a . Instructor's notes: Do not use a member function in your solution to this problem.
a [ n - 1 ] = - 1 ;
5. Given that an vector of int named a has been declared with 12 elements and that the integer variable k holds a value between 0 and 6. Assign 9 to the element just after a[k] .
a [ k + 1 ] = 9 ;
6. Given that an array of int named a has been declared with 12 elements and that the integer variable k holds a value between 2 and 8. Assign 22 to the element just before a[k] . Instructor's notes: This question works exactly the same for vectors, so just switch the name array with vector in the exercise description. In other words, think of a as a vector, not an array.
a [ k - 1 ] = 22 ;
7. An vector of int named a that contains exactly five elements has already been declared and initialized. In addition, an int variable j has also been declared and initialized to a value somewhere between 0 and 3.
Write a single statement that assigns a new value to the element of the vector indexed by j . This new value should be equal to twice the value stored in the next element of the vector (i.e. the element after the element indexed by j ). Do not modify any other elements of the vector!
a [ j ] = 2 * a [ j + 1 ] ;
Homework 9: VECTORS
1. Declare a vector named scores of twenty-five elements of type int .
vector < int > scores ( 25 ) ;
2. Given the vector a , write an expression that refers to the first element of the vector.
a [ 0 ]
3. Given an vector a , declared to contain 34 elements, write an expression that refers to the last element of the vector. Instructor's notes: Do not use a member function in your solution to this problem.
a [ 33 ]
4. Assume that the vector arr has been declared. In addition, assume that VECTOR_SIZE has been defined to be an integer that equals the number of elements in arr . Write a statement that assigns the next to last element of the vector to the variable x ( x has already been declared).
x = arr [ VECTOR_SIZE - 2 ] ;
5. Assume that the vector monthSales of integers has already been declared and that its elements contain sales data for the 12 months of the year in order (i.e., January, February, etc.). Write a statement that writes to standard output the element corresponding to October.
cout << monthSales [ 9 ] ;
6. Given that an vector of int named a has been declared, assign 3 to its first element.
a [ 0 ] = 3 ;
7. Assume that an vector of int variables named salarySteps that contains exactly five elements has been declared. Write a single statement to assign the value 30000 to the first element of this vector.
salarySteps [ 0 ] = 30000 ;
8. Assume that an vector of integers named salarySteps that contains exactly five elements has been declared. Write a statement that assigns the value 160000 to the last element of the vector salarySteps .
salarySteps [ 4 ] = 160000 ;
9. Assume that an vector named a , containing exactly five integers has been declared and initialized. Write a single statement that adds ten to the value stored in the first element of the vector.
a [ 0 ] += 10 ;
10. Given that an vector of int named a with 30 elements has been declared, assign 5 to its last element. Instructor's notes: Do not use a member function to answer this question.
a [ 29 ] = 5 ;
11. Assume v is a vector that has been declared and initialized. Write an expression whose true if there are any values stored in v.
! v. empty ( )
12. Assume v is a vector that has been declared and initialized. Write a statement that removes ALL the values stored in v.
v . clear ( ) ;
13. Assume v is a vector of integers that has been declared and initialized. Write a statement that adds the value 42 to the vector.
v . push_back ( 42 ) ;
Homework 8: Reference Parameters
1. Write the header for a function addOne that accepts a single integer reference parameter and returns nothing. Name the parameter x .
void addOne ( int & x )
2. Write a function addOne that adds 1 to its integer reference parameter. The function returns nothing.
void addOne ( int & x ) { x ++ ; }
Homework 8: Exchanges
1. 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 jtemp to j and i , respectively.
itemp = i ; jtemp = j ; i = jtemp ; j = itemp ;
itemp = i ; jtemp = j ; i = jtemp ; j = itemp ;
2. 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 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 .
temp = i ; i = j ; j = temp ;
3. Given two int variables, firstPlaceWinner and secondPlaceWinner , write some code that swaps their values. Declare any additional variables as necessary, but do not redeclare firstPlaceWinner and secondPlaceWinner .
int temp ; temp = firstPlaceWinner ; firstPlaceWinner = secondPlaceWinner ; secondPlaceWinner = temp ;
4. Given two double variables, bestValue and secondBestValue , write some code that swaps their values. Declare any additional variables as necessary.
double temp ; temp = bestValue ; bestValue = secondBestValue ; secondBestValue = temp ;
Homework 8: Definitions
1. Write the definition of a function printDottedLine , which has no parameters and doesn't return anything. The function prints to standard output a single line (terminated by a new line character) consisting of 5 periods.
void printDottedLine ( ) { cout << "....." << endl ; }
void printDottedLine ( ) { cout << "....." << endl ; }
2. Write the definition of a function printLarger , which has two int parameters and returns nothing. The function prints the larger value of the two parameters to standard output on a single line by itself. (For purposes of this exercise, the "larger" means "not the smaller".)
void printLarger ( int a , int b ) { if ( a > b ) cout << a << endl ; else cout << b << endl ; }
3. Write the definition of a function dashedLine , with one parameter, an int . If the parameter is negative or zero, the function does nothing. Otherwise it prints a complete line terminated by a new line character to standard output consisting of dashes (hyphens) with the parameter's value determining the number of dashes. The function returns nothing.
void dashedLine ( int n ) { if ( n <= 0 ) return ; while ( n > 0 ) { cout << '-' ; -- n; } cout << endl; }
Homework 8: Invocations invocations
1. printTodaysDate is a function that accepts no parameters and returns no value. Write a statement that calls printTodaysDate .
printTodaysDate ( ) ;
2. printErrorDescription is a function that accepts one int parameter and returns no value. Write a statement that calls the function printErrorDescription , passing it the value 14.
printTodaysDate ( ) ;
2. printErrorDescription is a function that accepts one int parameter and returns no value. Write a statement that calls the function printErrorDescription , passing it the value 14.
printErrorDescription ( 14 ) ;
3. printLarger is a function that accepts two int parameters and returns no value. Two int variables, sales1 and sales2 , have already been declared and initialized. Write a statement that calls printLarger , passing it sales1 and sales2 .
printLarger ( sales1 , sales2 ) ;
Homework 8: Declarations
1. Write a statement that declares a prototype for a function printErrorDescription , which has an int parameter and returns nothing.
void printErrorDescription ( int ) ;
2. Write a statement that declares a prototype for a function printLarger , which has two int parameters and returns no value.
void printErrorDescription ( int ) ;
2. Write a statement that declares a prototype for a function printLarger , which has two int parameters and returns no value.
void printLarger ( int , int ) ;
3. Write a statement that declares a prototype for a function twice , which has an int parameter and returns an int .
int twice ( int ) ;
Homework 7: Definitions
1. Write the definition of a function oneMore , which receives an integer parameter and returns an integer that is one more than the value of the parameter. So if the parameter's value is 7, the function returns the value 8. If the parameter's value happens to be 44, the functions returns the value 45.
int oneMore ( int x ) { return x + 1 ; }
int oneMore ( int x ) { return x + 1 ; }
2. Write the definition of a function oneLess , which receives an integer parameter and returns an integer that is one less than the value of the parameter. So if the parameter's value is 7, the function returns the value 6. If the parameter's value happens to be 44, the functions returns the value 43.
int oneLess ( int x ) { return x - 1 ; }
3. Write the definition of a function half , which receives an integer parameter and returns an integer that is half the value of the parameter. (Use integer division!) So if the parameter's value is 7, the function returns the value 3. If the parameter's value happens to be 44, the functions returns the value 22.
int half ( int x ) { return x / 2 ; }
4. Write the definition of a function square , which receives an integer parameter and returns the square of the value of the parameter. So if the parameter's value is 7, the function returns the value 49. If the parameter's value happens to be 25, the functions returns the value 625. If the value of the parameter is 0, the function returns 0.
int square ( int x ) { return x * x ; }
5. Write the definition of a function absoluteValue , that receives an integer parameter and returns the absolute value of the parameter's value. So, if the parameter's value is 7 or 803 or 141 the function returns 7, 803 or 141 respectively. But if the parameter's value is -22 or -57, the function returns 22 or 57 (same magnitude but a positive instead of a negative). And if the parameter's value is 0, the function returns 0.
int absoluteValue ( int x ) { return abs ( x ) ; }
6. Write the definition of a function signOf , that receives an integer parameter and returns a -1 if the parameter is negative, returns 0 if the parameter is 0 and returns 1 if the parameter is positive. So, if the parameter's value is 7 or 803 or 141 the function returns 1. But if the parameter's value is -22 or -57, the function returns -1. And if the parameter's value is 0, the function returns 0.
int signOf ( int x ) { if ( x < 0 ) { return - 1; } else if ( x == 0 ) { return 0; } else { return 1; } }
7. Write the definition of a function isPositive , that receives an integer parameter and returns true if the parameter is positive, and false otherwise. So, if the parameter's value is 7 or 803 or 141 the function returns true. But if the parameter's value is -22 or -57, or 0, the function returns false.
bool isPositive ( int x ) { if ( x > 0 ) { return true; } else { return false ; } }
8. Write the definition of a function isSenior , that receives an integer parameter and returns true if the parameter's value is greater or equal to 65, and false otherwise. So, if the parameter's value is 7 or 64 or 12 the function returns false. But if the parameter's value is 69 or 83 or 65 the function returns true.
bool isSenior ( int x ) { if ( x >= 65 ) { return true; } else { return false; } }
9. Write the definition of a function isEven , that receives an integer parameter and returns true if the parameter's value is even, and false otherwise. So, if the parameter's value is 7 or 93 or 11 the function returns false. But if the parameter's value is 44 or 126 or 7778 the function returns true.
bool isEven ( int x ) { if ( x % 2 == 0 ) { return true ; } else { return false ; } }
10. Write the definition of a function twice , that receives an integer parameter and returns an integer that is twice the value of that parameter.
int twice ( int x ) { return 2 * x ; }
11. Write the definition of a function add , which receives two integer parameters and returns their sum.
int add ( int x , int y ) { return x + y ; }
12. Write the definition of a function max that has three int parameters and returns the largest.
int max ( int a , int b, int c ) { return a < b ? ( b < c ? c : b ) : ( a < c ? c : a ); }
13. Write the definition of a function powerTo , which receives two parameters. The first is a double and the second is an int . The function returns a double . If the second parameter is negative, the function returns 0. Otherwise, it returns the value of the first parameter raised to the power of the second.
double powerTo ( double x , int n ) { double prod = 1.0; if ( n < 0 ) return 0.0; while ( n > 0 ) { prod *= x; --n; } return prod; }
Homework 7: Function Invocations
1. add is a function that accepts two int parameters and returns their sum. Two int variables, euroSales and asiaSales , have already been declared and initialized. Another int variable, eurasiaSales , has already been declared.Write a statement that calls add to compute the sum of euroSales and asiaSales and store this value in eurasiaSales .
eurasiaSales = add ( euroSales , asiaSales ) ;
2. toThePowerOf is a function that accepts two int parameters and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized. Another int variable, cubeVolume , has already been declared. Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3, and store this value in cubeVolume .
cubeVolume = toThePowerOf ( cubeSide , 3 ) ;
3. max is a function that accepts two int parameters and returns the value of the larger one. Two int variables, population1 and population2 , have already been declared and initialized. Write an expression (not a statement!) whose value is the larger of population1 and population2 by calling max .
max ( population1 , population2 )
eurasiaSales = add ( euroSales , asiaSales ) ;
2. toThePowerOf is a function that accepts two int parameters and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized. Another int variable, cubeVolume , has already been declared. Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3, and store this value in cubeVolume .
cubeVolume = toThePowerOf ( cubeSide , 3 ) ;
3. max is a function that accepts two int parameters and returns the value of the larger one. Two int variables, population1 and population2 , have already been declared and initialized. Write an expression (not a statement!) whose value is the larger of population1 and population2 by calling max .
max ( population1 , population2 )
4. max is a function that accepts two int parameters and returns the value of the larger one. Four int variables, population1 , population2 , population3 , and population4 have already been declared and initialized. Write an expression (not a statement!) whose value is the largest of population1 , population2 , population3 , and population4 by calling max . (HINT: you will need to call max three times and you will need to pass the return values of two of those calls as arguments to max . REMEMBER: write an expression, not a statement.)
max ( max ( population1 , population2 ) , max ( population3 , population4 ) )
Homework 7: Intro
1. Assume that the int variables i , j and n have been declared, and n has been initialized. Write code that causes a "triangle" of asterisks to be output to the screen, i.e., n lines should be printed out, the first consisting of a single asterisk, the second consisting of two asterisks, the third consisting of three, etc. The last line should consist of n asterisks. Thus, for example, if n has value 3, the output of your code should be (scroll down if necessary):
*
**
***
for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= i ; j ++ ) { cout << "*" ; } cout << endl ; }
*
**
***
for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= i ; j ++ ) { cout << "*" ; } cout << endl ; }
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
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
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 .
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
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.)
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
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 ;
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
( 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).
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 ;
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
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 .
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 ; }
# 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 ;
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 ;
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.
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:
cout << "Hello World " <<endl;
#include <iostream>
cout << "Turing,Alan " <<endl;
#include <iostream>
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;
}
Subscribe to:
Posts (Atom)